henryspace

记录精彩的程序人生 开始使用

Part 29 - Go 语言学习 - Gin 框架使用

gin框架使用

package main

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math/rand"
	"time"
)

func main() {
	r := gin.Default()
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}
	//  Middleware 调用
	r.Use(func(c *gin.Context) {
		s := time.Now()

		c.Next()

		logger.Info("Incoming request",
			zap.String("path", c.Request.URL.Path),
			zap.Int("status", c.Writer.Status()),
			zap.Duration("elapsed", time.Now().Sub(s)))
	}, func(c *gin.Context) {
		c.Set("requestid", rand.Int())
		c.Next()
	})

	r.GET("/ping", func(c *gin.Context) {
		h := gin.H{
			"message":"pong",
		}
		if rid, exsits := c.Get("requestid"); exsits {
			h["requestid"] = rid
		}

		c.JSON(200, h)
	})
	r.GET("/hello", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message":"hello",
		})
	})
	r.Run()
}

评论
留下你的脚步