Go语言上手(四)-Gin上手 | 青训营笔记

官方文档

快速入门 | Gin Web Framework (gin-gonic.com)

安装gin

PS H:\Gin> go get -u github.com/gin-gonic/gin

go.mod

module Gin

go 1.19

require (
	github.com/gin-contrib/sse v0.1.0 // indirect
	github.com/gin-gonic/gin v1.8.2 // indirect
	github.com/go-playground/locales v0.14.1 // indirect
	github.com/go-playground/universal-translator v0.18.0 // indirect
	github.com/go-playground/validator/v10 v10.11.1 // indirect
	github.com/goccy/go-json v0.10.0 // indirect
	github.com/json-iterator/go v1.1.12 // indirect
	github.com/leodido/go-urn v1.2.1 // indirect
	github.com/mattn/go-isatty v0.0.17 // indirect
	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
	github.com/modern-go/reflect2 v1.0.2 // indirect
	github.com/pelletier/go-toml/v2 v2.0.6 // indirect
	github.com/ugorji/go/codec v1.2.8 // indirect
	golang.org/x/crypto v0.5.0 // indirect
	golang.org/x/net v0.5.0 // indirect
	golang.org/x/sys v0.4.0 // indirect
	golang.org/x/text v0.6.0 // indirect
	google.golang.org/protobuf v1.28.1 // indirect
	gopkg.in/yaml.v2 v2.4.0 // indirect
)

可以看到项目下生成依赖

基础配置

package main

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

func main() {
	// 创建路由
	r := gin.Default()
	// 绑定路由
	r.GET("/", func(context *gin.Context) {
		context.String(http.StatusOK, "hello world !")
	})

	// 监听 默认为8080
	r.Run(":8000")
}

运行之后打开浏览器

输入地址

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Hd8LCTFG-1682231339666)(https://xingqiu-tuchuang-1256524210.cos.ap-shanghai.myqcloud.com/12640/image-20230118135510589.png)]

成功

json

map构造json
//json
data := map[int]interface{}{
   1: "1",
   2: "2",
   3: 3,
}
r.GET("/jsonByMap", func(context *gin.Context) {
   context.JSON(http.StatusOK, data)
})
{"1":"1","2":"2","3":3}
默认构造
r.GET("/jsonByDefault", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"1": 1,
			"2": 3,
		})
	})

查看源码

utils.go

// H is a shortcut for map[string]interface{}
type H map[string]any

H 是一个map 键-string 值- any 对 非标准的go sdk

使用结构体
r.GET("/jsonByStruct", func(context *gin.Context) {
   // 定义结构体
   type data struct {
      Name    string
      Message string
      Age     int
   }
   d := data{
      Name:    "bowen",
      Message: "hello",
      Age:     0,
   }
   context.JSON(http.StatusOK, d)
})
{"Name":"bowen","Message":"hello","Age":0}

注意 结构体的大写才能初始化 不能被解析 不能被导出

如果要使用别名 后加

`json:"name"`

get

普通请求

请求获取参数

query
r.GET("/get", func(context *gin.Context) {
   name := context.Query("query")
   context.JSON(http.StatusOK, name)
})

其他的api

DefaultQuery
// // DefaultQuery returns the keyed url query value if it exists,
 otherwise it returns the specified defaultValue string.
 See: Query() and GetQuery() for further information.
     GET /?name=Manu&lastname=
     c.DefaultQuery("name", "unknown") == "Manu"
     c.DefaultQuery("id", "none") == "none"
     c.DefaultQuery("lastname", "none") == ""
func (c *Context) DefaultQuery(key, defaultValue string) string {
    xxx
}

也就是默认的参数,取不到第一个参数就返回使用默认的第二个参数

GetQuery
// GetQuery is like Query(), it returns the keyed url query value
// if it exists `(value, true)` (even when the value is an empty string),
// otherwise it returns `("", false)`.
// It is shortcut for `c.Request.URL.Query().Get(key)`
//     GET /?name=Manu&lastname=
//     ("Manu", true) == c.GetQuery("name")
//     ("", false) == c.GetQuery("id")
//     ("", true) == c.GetQuery("lastname")
func (c *Context) GetQuery(key string) (string, bool) {
xxx
}

也就是会返回两参数 第一个为取得值,第二个为是否取到参数(bool)

获取url参数
/:name/:age

加上:可以获取name和age的值

name := context.Param("name")

Post

PostForm
name := context.PostForm("name")

取不到返回空字符串

DefaultPostForm

与上面的get请求类似

取到返回值,否则为默认值

GetPostForm

和上面的get类似

绑定结构体

使用ShouldBind()方法

注意要传递地址 使用&

源码

// ShouldBind checks the Method and Content-Type to select a binding engine automatically,
// Depending on the "Content-Type" header different bindings are used, for example:
//     "application/json" --> JSON binding
//     "application/xml"  --> XML binding
// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
// It decodes the json payload into the struct specified as a pointer.
// Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid.
func (c *Context) ShouldBind(obj any) error {
   b := binding.Default(c.Request.Method, c.ContentType())
   return c.ShouldBindWith(obj, b)
}

同时使用反射,动态获取

这里定义结构体必须大写,不然无法取到结构体的字段

这里定义结构体要指定

Gin中提供了模型绑定,将表单数据和模型进行绑定,方便参数校验和使用。

使用如下

// 表单数据
type LoginForm struct {
    UserName  string    `form:"username"`    
    Password  string    `form:"password"`
    Email	  string    `form:"email"`  
}

如果匹配不上赋值为空

可以混合使用

type student struct {
	Username string `form:"username" json:"username"`
	Password string `form:"password" json:"password"`
}

互不影响

文件上传

单个文件上传

FormFile方法会读取参数“upload”后面的文件名,返回值是一个File指针,和一个FileHeader指针,和一个err错误。

router.POST("/upload", func(c *gin.Context) {
		// 单文件
		file, _ := c.FormFile("file")
		log.Println(file.Filename)

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

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

请求重定向

请求重定向

内部重定向

context.Redirect(http.StatusMovedPermanently, "http://localhost/8000/index")

路由重定向

r.GET("redirect", func(context *gin.Context) {
		context.Request.URL.Path = "/index"
		r.HandleContext(context)
	})
路由重定向

路由分组

// 设置路由
router := gin.Default()
// 第一个参数是:路径; 第二个参数是:具体操作 func(c *gin.Context)
router.GET("/Get", getting)
router.POST("/Post", posting)
router.PUT("/Put", putting)
router.DELETE("/Delete", deleting)
router.Any('/any',any) //任何类型
route.NoRoute() //不存在的请求
// 默认启动的是 8080端口
router.Run()
路由组
// 两个路由组,都可以访问,大括号是为了保证规范
v1 := r.Group("/v1")
{
    // 通过 localhost:8080/v1/hello访问,以此类推
    v1.GET("/hello", sayHello)
    v1.GET("/world", sayWorld)
}
v2 := r.Group("/v2")
{
    v2.GET("/hello", sayHello)
    v2.GET("/world", sayWorld)
}
r.Run(":8080")
大量路由实现

当我们的路由变得非常多的时候,那么建议遵循以下步骤:

  1. 建立routers包,将不同模块拆分到多个go文件
  2. 每个文件提供一个方法,该方法注册实现所有的路由
  3. 之后main方法在调用文件的方法实现注册
// 这里是routers包下某一个router对外开放的方法 传入变量的指针
func LoadRouter(e *gin.Engine) {
    e.Group("v1")
    {
        v1.GET("/post", postHandler)
  		v1.GET("/get", getHandler)
    }
  	...
}

中间件

相当于java的拦截器

// 中间件
func indexHandler(context *gin.Context) {
	fmt.Println("中间件")
	fmt.Println("index开始执行")
	context.Next()
    // 阻止调用 context.Abort()
	fmt.Println("index执行结束")
}
func lastHandler(context *gin.Context) {
	fmt.Println("执行last")
}
r.GET("/indexHandler", indexHandler, lastHandler)

中间件
index开始执行
执行last
index执行结束

gin.defalut()默认使用logger()和recover的中间件

使用协程使用copy并发

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值