部分範例
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)