go-gin框架初探
2021-05-08 本文已影响0人
超鸽带你飞
gin框架初探
- 参数req的获取、修改、封装
- 路由定义(底层结构:前缀树)
- 全局中间件、路由中间件
- run的几种方式
- 响应resp
package main
import (
"bytes"
"fmt"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
"io/ioutil"
"log"
"net/http"
"time"
)
var (
g errgroup.Group
)
const CtxRequestParamKey string = "CtxRequestParamKey"
type Out struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
func NewOut(code int, msg string, data interface{}) *Out {
return &Out{
Code: code,
Msg: msg,
Data: data,
}
}
func GetReqValFromRequest(ctx *gin.Context, key string) string {
if val, ok := ctx.Cookie(key); ok == nil {
return val
} else if val, ok := ctx.GetPostForm(key); ok {
return val
} else if val, ok := ctx.GetQuery(key); ok {
return val
}
return ""
}
func SetRequestParam(ctx *gin.Context) map[string]string {
RequestParam := make(map[string]string)
//ctx中没有获取全部请求参数的方法
//get
if get := ctx.Request.URL.Query(); len(get) > 0 {
for k, v := range get {
RequestParam[k] = ""
if len(v) > 0 {
RequestParam[k] = v[0]
}
}
}
//post
req := ctx.Request
if err := req.ParseForm(); err == nil {
if post := req.PostForm; len(post) > 0 {
for k, v := range post {
RequestParam[k] = ""
if len(v) > 0 {
RequestParam[k] = v[0]
}
}
}
}
ctx.Set(CtxRequestParamKey, RequestParam)
return RequestParam
}
func ParamMiddleware(ctx *gin.Context) {
//get原始数据
fmt.Println("rawQuery:", ctx.Request.URL.RawQuery)
fmt.Println("Query:", ctx.Request.URL.Query())
//body原始数据
input, _ := ctx.GetRawData() //通过url参数传递通过ctx.GetRawData无法获取
//必须恢复body的内容
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(input))
fmt.Println("GetRawData:", string(input))
//添加自定义参数
ctx.Request.ParseForm()
fmt.Println("ParseForm-form:", ctx.Request.Form) //get+post
fmt.Println("ParseForm-postForm:", ctx.Request.PostForm) //post
ctx.Request.PostForm.Set("lyc","1111")
SetRequestParam(ctx)
ctx.Next()
}
func ParsePhoneMiddleware(c *gin.Context) {
fmt.Println("middle start")
phone:=GetReqValFromRequest(c,"phone")
fmt.Println("phone",phone)
c.Next()
fmt.Println("middle end")
}
func MyLogger(ctx *gin.Context){
t := time.Now()
ctx.Next()
log.Print("Cost:",time.Since(t))
}
//curl -d '{"login": "admin", "pass": "123"}' -H 'Content-Type: application/json' http://127.0.0.1:9527?id=1&name=lyc
//curl -d 'login=admin&pass=123' http://127.0.0.1:9527?id=1&name=lyc
//curl http://127.0.0.1:9527/test
func SetRouter(router *gin.Engine) {
r := router
//全局中间件
router.Use(func(ctx *gin.Context) {
ParamMiddleware(ctx)
//通用日志打点
MyLogger(ctx)
})
//r.Use(ParamMiddleware)
//r.Use(MyLogger)
r.Any("/", ParsePhoneMiddleware,func(ctx *gin.Context) {
fmt.Println("first .........")
requestParam := ctx.GetStringMapString(CtxRequestParamKey)
fmt.Println(requestParam)
name,ok:=requestParam["name"]
fmt.Println(name,ok)
out := NewOut(0, "success", nil) //{"code":0,"msg":"success","data":null}%
//out.Data = map[string]interface{}{} //{"code":0,"msg":"success","data":{}}%
//out.Data = [0]int{} //{"code":0,"msg":"success","data":[]}%
out.Data = requestParam
ctx.JSON(200, out)
})
r.Any("/test", func(ctx *gin.Context) {
ctx.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
})
}
func main() {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
SetRouter(r)
// 监听并在 0.0.0.0:9527 上启动服务
r.Run(":9527")
//优雅重启
//endless.ListenAndServe(":9527", r)
//自定义HTTP配置
//http.ListenAndServe(":9527", r)
//或者
//s := &http.Server{
// Addr: ":9527",
// Handler: r,
// ReadTimeout: 10 * time.Second,
// WriteTimeout: 10 * time.Second,
// MaxHeaderBytes: 1 << 20,
//}
//s.ListenAndServe()
//Gin运行多个服务
//g.Go(func() error {
// return s.ListenAndServe()
//})
//g.Go(func() error {
// return s1.ListenAndServe()
//})
//if err := g.Wait(); err != nil {
// log.Fatal(err)
//}
}