Go-Gin之接口开发


Go-gin学习笔记

请移步其他技术文档

Gin Web Fram快速入门

GORM

topgoer

studygolang


代码段

(1)渲染模板

r := gin.Default()
r.LoadHTMLGlob("templates/**/*")
r.GET("/home/index", func(c *gin.Context) {
	c.HTML(http.StatusOK, "home/index.tmpl", gin.H{
		"title": "Users",
	})
	// 模板文件位于 templates/home/index.tmpl
})

若报错,模板头部需要加{⋅{ define "home/index.tmpl" }}、尾部{⋅{ end }}

(2)HTTP相关

请求方式

//GET
id := c.Query("id")
//POST
name := c.PostForm("name")
//设置默认值
page := c.DefaultQuery("page", "1")

上传文件

//import ("net/http" "github.com/gin-gonic/gin" "time" "fmt" "path" "log")
//r.MaxMultipartMemory = 8 << 20
r.POST("/upload", func(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	
	dst := path.Join("./uploads", file.Filename)
	// 上传文件至指定目录
	c.SaveUploadedFile(file, dst)

	log.Println(dst)

	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})

重定向

r.GET("/test", func(c *gin.Context) {
	// 301重定向
	c.Redirect(http.StatusMovedPermanently, "http://www.alibaba.com/")
})

r.POST("/test2", func(c *gin.Context) {
	// 302重定向
	c.Redirect(http.StatusFound, "/foo")
})

// 内部重定向
r.GET("/test", func(c *gin.Context) {
	c.Request.URL.Path = "/test2"
	r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
	c.JSON(200, gin.H{"hello": "world"})
})

静态文件

r.Static("/assets", "./assets")
//r.StaticFS("/more_static", http.Dir("my_file_system"))
r.StaticFile("/favicon.ico", "./assets/favicon.ico")

(3)数据库

数据库连接

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"net/url"
)

var DB *gorm.DB

func InitDB() *gorm.DB {
	host := viper.GetString("datasource.host")
	port := viper.Get("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	loc := viper.GetString("datasource.loc")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=%s",
		username,
		password,
		host,
		port,
		database,
		charset,
		url.QueryEscape(loc))
	fmt.Println(args)
	db, err := gorm.Open(mysql.Open(args), &gorm.Config{})
	if err != nil {
		fmt.Println(err)
		panic("databases_error:"+err.Error())
	}
	DB = db
	return db
}

数据库查询

// 增
acco := &model.AdminUser{
	Phone:     "16522223336",
	User_name: "uauauaua",
	Password:  "uauauauauauauauauauauauauauauauau"}
util.DB.Create(acco)

// 改
upr := util.DB.Where("phone = ?", "18600007360").Updates(&model.AdminUser{User_name: "66699"})

if upr.RowsAffected > 0 {
	// 修改成功
}
// 删
der := util.DB.Where("phone = ?", "16522223333").Delete(&model.AdminUser{})
if der.RowsAffected > 0 {
	// 删除成功
}

// 查
admin_users := []model.AdminUser{}
util.DB.Find(&admin_users)

GORM参考