gin框架入门使用

216 阅读2分钟

server最基本使用

func main() {
   //创建路由
   r := gin.Default()

   //确定路由规则,执行的函数
   //gin.context  封装了response和request
   r.GET("/", func(c *gin.Context) {
      c.String(http.StatusOK, "hello world")
   })

   //监听端口 不写的时候默认8080
   r.Run(":8080")
}
r.POST
r.DELETE  表示不同的访问方法

访问路由分组

func main() {
   router := gin.Default()

   v1 := router.Group("/v1")
   {
      v1.GET("/hello", sayhello)
      v1.GET("/world", sayworld)
   }

   v2 := router.Group("/v2")
   {
      v2.GET("/hello", sayhello)
      v2.GET("/world", sayworld)
   }

   router.Run()
}

func sayhello(context *gin.Context) {
   context.String(http.StatusOK, "say hello")
}

func sayworld(context *gin.Context) {
   context.String(http.StatusOK, "say world")
}

{3EF3D935-6649-43AB-A4B0-0413FB5E0AF9}.png.jpg

路径参数

只能匹配 /user/xxx 这种格式
router.GET("/user/:name", func(context *gin.Context) {
   name := context.Param("name")
   context.String(http.StatusOK, "hello %s", name)
})
能匹配 /user/xxx/other1/other2
router.GET("/user/:name/*action", func(context *gin.Context) {
   name := context.Param("name")
   action := context.Param("action")
   message := name + " do  " + action
   context.String(http.StatusOK, message)
})

image.png

{AA97C892-EF40-4FAD-840B-BBAA8B03431A}.png.jpg 如图所示 action参数获取的是name后的整体

另一种获取url中参数的方法:

router.GET("/user", func(context *gin.Context) {
   //获取url参数中的name 如果没有设置为默认值normal
   name := context.DefaultQuery("name", "tttlf")
   //获取url参数中的age 不指定默认值
   age := context.Query("age")

   context.String(http.StatusOK, "his name is %s and his age is %s", name, age)
})

POST方法使用:

router.POST("/form", func(context *gin.Context) {
   //放在body里面的字段
   types := context.DefaultPostForm("type", "post")
   username := context.PostForm("username")
   pwd := context.PostForm("pwd")

   //可以get + post混合使用 url里面再传一个字段
   name := context.Query("name")

   //返回json格式数据
   context.JSONP(200, gin.H{
      "username": username,
      "pwd":      pwd,
      "types":    types,
      "name":     name,
   })
})

文件获取:

router.MaxMultipartMemory = 8 << 20 //8mb
router.POST("/upload", func(context *gin.Context) {
   //获取表单传递文件
   file, err := context.FormFile("file")
   if err != nil {
      context.String(500, "上传文件出错")
   }

   //保存文件到本地指定位置
   context.SaveUploadedFile(file, "C:\Users\PC-11\Desktop"+file.Filename)
   context.String(http.StatusOK, "filename:%s", file.Filename)
})

多个文件获取:

router.POST("/uploadfiles", func(context *gin.Context) {
   //获取multipartform
   form, err := context.MultipartForm()
   if err != nil {
      context.String(http.StatusBadRequest, fmt.Sprintf("get err %s"), err.Error())
   }

   //获取所有文件  文件是通过post表单传递过来
   files := form.File["files"]
   for _, file := range files {
      fmt.Println(file.Filename)
   }
   context.String(200, "updload ok %d files", len(files))
})

接受处理: ->定义接收结构体:


type Login struct {
   // binding : "required" 申明这个要求的字段 如果传进来的数据为空值则会报错
   // form标签的值表示参数传递时 该字段名字必须为username、password 要不然接收不到
   User     string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"`
   Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
}

content-type 绑定 用该绑定之前要设置要结构体字段中的tag(推荐)

router.POST("/login", func(context *gin.Context) {
   var login Login

   //默认form格式
   if err := context.Bind(&login); err != nil {
      context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
   }

   //返回数据
   context.JSON(http.StatusOK, gin.H{
      "status":   "200",
      "user":     login.User,
      "password": login.Password,
   })
})

指定json绑定 参数传递一定要用json格式

router.POST("/jsonLogin", func(context *gin.Context) {
   var login Login

   //将request body中的数据按json格式解析到结构体
   if err := context.ShouldBindJSON(&login); err != nil {

      //如果发送的不是json格式 那么输出错误 而且传入json字段的命名必须按照tag中设置的名字来
      context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
   }

   context.JSON(http.StatusOK, gin.H{
      "status":   200,
      "username": login.User,
      "pwd":      login.Password,
   })

})

数据返回类型 1、json

//json
router.GET("/someJson", func(context *gin.Context) {
   context.JSON(http.StatusOK, gin.H{
      "username": "json",
      "password": "666666",
   })
})

{A0470AEA-E3B8-4ED9-933F-149010B9259F}.png.jpg

2、xml

router.GET("someXml", func(context *gin.Context) {
   context.XML(http.StatusOK, gin.H{
      "message": "tttlf",
   })
})

image.png

3、yaml

router.GET("someYaml", func(context *gin.Context) {
   context.YAML(200, gin.H{
      "name": "tttlf",
   })
})

image.png

重定向

router.GET("/index", func(context *gin.Context) {
   context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
})

会话控制

1、cookie相关
router.GET("/getCookie", func(context *gin.Context) {
   cookie, err := context.Cookie("key_cookie")
   if err != nil {
      cookie = "cookie"
      context.SetCookie("key_cookie", "value_cookie", //参数 1、2 是key和value
         60,          //生存时间
         "/",         //所在目录
         "localhost", //域名
         false,       //安全相关 是否通过https访问
         true)        //安全相关  是否允许别人通过is获取自己的cookie
   }
   fmt.Printf("cookie is value of: %s\n", cookie)
})
//session相关
//注意该密匙不要泄露
store := cookie.NewStore([]byte("secret"))
//路由上加上 session中间件
router.Use(sessions.Sessions("mySeesion", store))

router.GET("/setSession", func(context *gin.Context) {
   //设置session
   session := sessions.Default(context)
   session.Set("key", "value")
   session.Save()
})

router.GET("/getSession", func(context *gin.Context) {
   //获取session
   session := sessions.Default(context)
   v := session.Get("key")
   fmt.Println(v)
})