Gin框架入门

 1.安装并引入

$ go get -u github.com/gin-gonic/gin

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

2.创建服务

//创建服务
ginServer := gin.Default()
//处理请求
ginServer.GET("/hello", func(context *gin.Context) {
   context.JSON(200, gin.H{"msg": "hello"})
})
//指定服务器端口
ginServer.Run(":8082")

3.加载静态资源并访问页面

// 加载静态页面
ginServer.LoadHTMLGlob("templates/*")
//响应页面
ginServer.GET("index", func(context *gin.Context) {
   context.HTML(http.StatusOK, "index.html", gin.H{
      "msg": "hello",
   })
})

4.加载资源文件并访问页面

//加载资源文件
ginServer.Static("static", "./static")
ginServer.GET("index", func(context *gin.Context) {
   context.HTML(http.StatusOK, "index.html", gin.H{
      "msg": "hello",
   })
}) 

 5.传递参数

ginServer.GET("usr/info", func(context *gin.Context) {
   userid := context.Query("userid")
   username := context.Query("username")
   context.HTML(http.StatusOK, "index.html", gin.H{
      "userid":   userid,
      "username": username,
   })
})

6.restful传递参数 

//localhost:8082/user/info/100/user
ginServer.GET("user/info/:userid/:username", func(context *gin.Context) {
   userid := context.Param("userid")
   username := context.Param("username")
   context.HTML(http.StatusOK, "index.html", gin.H{
      "userid":   userid,
      "username": username,
   })
})

7.接收并返回json

ginServer.POST("/json", func(context *gin.Context) {
   // request.body
   data, _ := context.GetRawData()
   var m map[string]interface{}
   json.Unmarshal(data, &m)
   context.JSON(http.StatusOK, m)
})

8.表单提交

ginServer.POST("/user/add", func(context *gin.Context) {
   username := context.PostForm("username")
   pwd := context.PostForm("pwd")
   context.JSON(http.StatusOK, gin.H{
      "username": username,
      "userpwd":  pwd,
   })
})

9.重定向和404

// 重定向
ginServer.GET("/redirect", func(context *gin.Context) {
   context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
})
// 404
ginServer.NoRoute(func(context *gin.Context) {
   context.HTML(http.StatusNotFound, "404.html", nil)
})

10.中间件 

func myHandler() gin.HandlerFunc {
   return func(ctx *gin.Context) {
      ctx.Set("userSession", "userid-1")
      ctx.Next() //放行
      //ctx.Abort()//阻止
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值