使用gin来创建简单的http服务器

Gao
最近需要对Web服务进行重构,由于原先的martini已经不再维护了,所以更换为gin。 gin相对于原先的服务,使用起来相对更简单一些 服务启动: ```go import ( "fmt" "time" "net/http" "db" "github.com/gin-gonic/gin" ) func main() { r := gin.New() gin.SetMode(gin.ReleaseMode) db.SetupDB() r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n", param.ClientIP, param.TimeStamp.Format(time.RFC1123), param.Method, param.Path, param.Request.Proto, param.StatusCode, param.Latency, param.Request.UserAgent(), param.ErrorMessage, ) })) // Add this to disable logging // gin.DefaultWriter = ioutil.Discard r.GET("/address", HandleAddress) r.GET("/healthz", HandleHealthz) addr := fmt.Sprintf("%s:%d", "0.0.0.0", "80") s := &http.Server{ Addr: addr, Handler: r, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() } ``` 配置handler ```go import ( "fmt" "os" "github.com/gin-gonic/gin" ) type Query struct { IP string `form:"ip"` Type string `form:"type"` } func HandleAddress(c *gin.Context) { var query Query if c.ShouldBind(&query) == nil { ip := query.IP typ := query.Type switch typ { case "v6": out, err := db.FindV6Addr(ip) if err != nil { c.String(500, err.Error()) } else { c.JSON(200, out) } default: out, err := db.FindV4Addr(ip) if err != nil { c.String(500, err.Error()) } else { c.JSON(200, out) } } } else { c.String(500, "not support.") } } ``` 配置好后测试了性能: 开日志性能 `90_000 RPS` 关日志性能 `180_000 RPS` 大约比原先martini提高了一倍性能