Skip to content

Instantly share code, notes, and snippets.

@miclle
Created July 31, 2020 02:36
Show Gist options
  • Save miclle/75ab1291735eaf237d7a14b99e3329be to your computer and use it in GitHub Desktop.
Save miclle/75ab1291735eaf237d7a14b99e3329be to your computer and use it in GitHub Desktop.
Gin
package application
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Engine for server
type Engine struct {
*gin.Engine
}
// NewEngine return engine instance
func NewEngine() *Engine {
router := gin.New()
router.Use(logger.RouterLogger(nil))
router.Use(gin.Recovery())
engine := &Engine{}
engine.Engine = router
return engine
}
// Run the engine
func (engine *Engine) Run(addr string) {
engine.Engine.Run(addr)
}
// --------------------------------------------------------------------
// Context with engine
type Context struct {
context *gin.Context
// TODO
// Logger *logger.Logger
}
func (c *Context) Abort() {
c.context.Abort()
}
// HandlerFunc middleware
type HandlerFunc func(*Context) (res interface{}, err error)
// --------------------------------------------------------------------
// GET is a shortcut for router.Handle("GET", path, handle).
func (engine *Engine) GET(relativePath string, handlers ...HandlerFunc) gin.IRoutes {
return engine.handle(http.MethodGet, relativePath, handlers...)
}
func (engine *Engine) handle(httpMethod, relativePath string, handlers ...HandlerFunc) gin.IRoutes {
var handlersChain gin.HandlersChain
context := &Context{}
for index, handler := range handlers {
f := func(i int, h HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
context.context = c
// if context.Logger == nil {
// context.Logger = logger.New(c)
// }
res, err := h(context)
if context.context.IsAborted() {
return
}
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, err.Error())
return
}
// TODO
// last handler default return
if i == len(handlers)-1 {
c.JSON(http.StatusOK, res)
} else {
c.Next()
}
}
}
handlersChain = append(handlersChain, f(index, handler))
}
return engine.Engine.Handle(httpMethod, relativePath, handlersChain...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment