Gin框架

Gin

快速入门

go 复制代码
package main
import gin "github.com/gin-gonic/gin"

func main() {
	engine := gin.Default()
	engine.GET("/", func(c *gin.Context) {
		c.String(200, "Hello Gin")
	})
	engine.Run(":8888")
}

路由基础

go 复制代码
package main

import (
	gin "github.com/gin-gonic/gin"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}
func main() {
	engine := gin.Default()
	engine.LoadHTMLGlob("templates/*") //配置页面模板的位置
	engine.GET("/", func(c *gin.Context) {
		c.String(200, "Hello Gin")
	})
	engine.GET("/ping", func(c *gin.Context) {
		//json.Marshal();
		c.String(200, "pong")
	})
	engine.GET("json", func(c *gin.Context) {
		c.JSON(200, map[string]interface{}{
			"success": true,
			"data": map[string]interface{}{
				"arr": []int{
					10, 20,
				},
			},
		})
	})
	engine.GET("/ch", func(c *gin.Context) {
		c.JSON(200, gin.H{ //H 就是map[string]interface{}
			"success": true,
		})
	})

	engine.GET("/struct", func(c *gin.Context) {
		a := &User{
			Name: "user",
			Age:  0,
		}
		c.JSON(200, a)
		//c.XML(200, a)//返回xml

		//c.HTML(200, "index.html", gin.H{}) //渲染这个模板

		value := c.Query("aid")
		c.String(200, "aid:%s", value)
	})

	engine.Run(":8888")
}
//前端的使用 {.name}

模板渲染

go 复制代码
func main() {
  router := gin.Default()
  router.LoadHTMLGlob("templates/*")
  //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
  router.GET("/index", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.tmpl", gin.H{
      "title": "Main website",
    })
  })
  router.Run(":8080")
}
//多层目录
  router.LoadHTMLGlob("templates/**/*")
html 复制代码
{{ define "posts/index.html" }} 配置文件

<html>
  <h1>
    {{ .title }}
  </h1>
</html>
go 复制代码
func main() {
  router := gin.Default()
  router.Static("/assets", "./assets")
  router.StaticFS("/more_static", http.Dir("my_file_system"))
  router.StaticFile("/favicon.ico", "./resources/favicon.ico")

  // 监听并在 0.0.0.0:8080 上启动服务
  router.Run(":8080")
}
  • 获取参数
go 复制代码
func main() {
  router := gin.Default()

  router.POST("/post", func(c *gin.Context) {

    id := c.Query("id")//这个只能获取post的数据
    page := c.DefaultQuery("page", "0")
    name := c.PostForm("name")//这个只能获得post的数据
    message := c.PostForm("message")

    fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
  })
  router.Run(":8080")
}
  • 将参数绑定到结构体
go 复制代码
package main

import (
  "log"
  "time"

  "github.com/gin-gonic/gin"
)
type Person struct {
  Name     string    `form:"name"`
  Address  string    `form:"address"`
  Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
}
func main() {
  route := gin.Default()
  route.GET("/testing", startPage)
  route.Run(":8085")
}
func startPage(c *gin.Context) {
  var person Person
  // 如果是 `GET` 请求,只使用 `Form` 绑定引擎(`query`)。
  // 如果是 `POST` 请求,首先检查 `content-type` 是否为 `JSON` 或 `XML`,然后再使用 `Form`(`form-data`)。
  // 查看更多:https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88
  if c.ShouldBind(&person) == nil {
    log.Println(person.Name)
    log.Println(person.Address)
    log.Println(person.Birthday)
  }
  c.String(200, "Success")
}
  • 获取原始数据 c.GetRawData()

路由

go 复制代码
package main
 
import (
    "github.com/gin-gonic/gin"
    "net/http"
)
 
func main() {
    r := gin.Default()
    
    // 创建一个基础路由组
    api := r.Group("/api")
    {
        api.GET("/users", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"message": "获取用户列表"})
        })
        api.POST("/users", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"message": "创建新用户"})
        })
    }
    
    r.Run(":8080")
}

中间件

  • 外部中间件
  • 全局中间件
  • 分组中间件
  • 中间件和控制器的数据共享
  • c.set("user","scc") c.get("user")
  • c.copy() 拷贝一个gin.Context

上传文件

go 复制代码
func main() {
  router := gin.Default()
  // 为 multipart forms 设置较低的内存限制 (默认是 32 MiB)
  router.MaxMultipartMemory = 8 << 20  // 8 MiB
  router.POST("/upload", func(c *gin.Context) {
    // 单文件
    file, _ := c.FormFile("file")
    log.Println(file.Filename)

    dst := "./" + file.Filename
    // 上传文件至指定的完整文件路径
    c.SaveUploadedFile(file, "./files/" + file.Filename)

    c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
  })
  router.Run(":8080")
}
  • path.join() 拼接路径
go 复制代码
import (
    "fmt"

    "github.com/gin-gonic/gin"
)

func main() {

    router := gin.Default()

    router.GET("/cookie", func(c *gin.Context) {

        cookie, err := c.Cookie("gin_cookie")

        if err != nil {
            cookie = "NotSet"
            c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
        }

        fmt.Printf("Cookie value: %s \n", cookie)
    })

    router.Run()
}

session

  • 要去下载三方库

Gorm

https://gorm.io/zh_CN/

go-ini

https://ini.unknwon.io/docs/intro/getting_started

相关推荐
不会聊天真君6473 天前
介绍(gin笔记第一期)
笔记·gin
ZHENGZJM4 天前
Server-Sent Events (SSE) 接口实现
架构·go·gin
ZHENGZJM4 天前
统一响应封装与 API 错误处理
react.js·go·gin
ZHENGZJM4 天前
仓库抓取与内容提取
go·gin
GDAL5 天前
gin.H 深入全面讲解
gin·h
呆萌很5 天前
【Gin】参数处理练习题
gin
GDAL5 天前
gin.Default() 深入全面讲解
golang·go·gin
GDAL7 天前
为什么选择gin?
golang·gin
ZHENGZJM10 天前
Gin 鉴权中间件设计与实现
中间件·gin
ZHENGZJM11 天前
认证增强:图形验证码、邮箱验证与账户安全
安全·react.js·go·gin