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

相关推荐
pedestrian_h12 小时前
gin框架学习笔记
笔记·学习·go·web·gin
唐僧洗头爱飘柔95272 天前
(Go Gin)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
后端·golang·go·restful·gin·goweb开发
一个热爱生活的普通人4 天前
GIN 服务如何实现优雅停机
go·gin
chxii4 天前
3.1goweb框架gin下
gin
Delphi菜鸟7 天前
go+mysql+cocos实现游戏搭建
mysql·游戏·golang·gin·cocos2d
老朋友此林10 天前
go语言学习笔记:gin + gorm + mysql 用户增删改查案例入门
mysql·golang·gin
梦兮林夕12 天前
06 文件上传从入门到实战:基于Gin的服务端实现(一)
后端·go·gin
能来帮帮蒟蒻吗24 天前
GO语言学习(16)Gin后端框架
开发语言·笔记·学习·golang·gin
Json201131525 天前
Gin、Echo 和 Beego三个 Go 语言 Web 框架的核心区别及各自的优缺点分析,结合其设计目标、功能特性与适用场景
前端·golang·gin·beego