Gin
Gin 教學
部分範例
func startGinHttpServer(err chan error) {
gin.SetMode(gin.ReleaseMode)
engine := gin.New()
loadRoutes(engine)
apis.StartHttpServer(err, engine)
}
func StartHttpServer(errChan chan error, engine *gin.Engine) {
endpoint := fmt.Sprintf(":%d", config.ConfigData.Service.Port)
go func() {
errChan <- engine.Run(endpoint)
}()
zap.S().Infof("Listening on port: %d", config.ConfigData.Service.Port)
}
func NewHandler(base *gin.RouterGroup, ) {
base.GET("/info", handler.GetInfo)
base.PUT("/info", handler.UpdateInfo)
}
func (a *InfoHandler) GetInfo(c *gin.Context) {
//call usecase method
info, _ := a.CUsecase.GetInfo()
c.JSON(http.StatusOK, info)
}
func (a *InfoHandler) UpdateInfo(c *gin.Context) {
body := models.Info{}
//gin example bind body
if err := c.BindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, err)
return
}
//call usecase method
err := a.CUsecase.Update(&body)
if err != nil {
c.JSON(http.StatusExpectationFailed, err)
return
}
c.JSON(http.StatusOK, "ok")
}
中間件
如果沒特別處理,一般就會顯示 not found string預設顯示
r.NoMethod(HandleNotFound)
r.NoRoute(HandleNotFound)
rate limiter
希望API不要被特定節點頻繁存取以致於造成伺服器端的過載
參考文章
筆記
What you're looking for is the NoRoute
handler.
Rate limiting 通常在很多開放API的服務內會常看到, 像是Twitter, 像是Facebook或是新浪微博, 其目的就是希望API不要被特定節點頻繁存取以致於造成伺服器端的過載
Last updated