Created
July 31, 2020 02:36
-
-
Save miclle/75ab1291735eaf237d7a14b99e3329be to your computer and use it in GitHub Desktop.
Gin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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