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

相关推荐
驰羽3 天前
[GO]gin框架:ShouldBindJSON与其他常见绑定方法
开发语言·golang·gin
千码君20168 天前
Go语言:记录一下Go语言系统学习的第一天
java·开发语言·学习·golang·gin·并发编程·编译语言
会跑的葫芦怪23 天前
Gin 框架令牌桶限流实战指南
驱动开发·gin
Stars202424 天前
【gin框架读取参数的方式】
iphone·xcode·gin
会跑的葫芦怪1 个月前
Go tool pprof 与 Gin 框架性能分析完整指南
开发语言·golang·gin
n8n1 个月前
Gin 框架令牌桶限流实战指南
go·gin
n8n1 个月前
Go tool pprof 与 Gin 框架性能分析完整指南
go·gin
kite01211 个月前
Gin + JWT 认证机制详解:构建安全的Go Web应用
golang·gin·jwt
T0uken1 个月前
【Golang】Gin:静态服务与模板
开发语言·golang·gin
希望20171 个月前
Golang | http/server & Gin框架简述
http·golang·gin