Open zxysilent opened 5 years ago
Use the AbortWithStatusJSON function in gin to achieve echo-like effects.
package main
import (
"github.com/gin-gonic/gin"
)
func check() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.URL.Path != "/test" {
c.AbortWithStatusJSON(500, gin.H{"message": "path fail"})
}
}
}
func main() {
r := gin.Default()
r.Use(check())
r.GET("/test", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "path ok"})
})
r.Run()
}
// curl 127.0.0.1:8080/test/haha
// {"message":"path fail"}
// curl 127.0.0.1:8080/test
// {"message":"path ok"}
You could try https://github.com/sleagon/ginfmt to handle your error/succ response easily~
With issues:
go version: go version go1.12.5 windows/amd64
gin version (or commit ref): v1.4.0
operating system: windows 10 amd 64
Description
How to custom http error handling
Screenshots
eg https://echo.labstack.com/guide/error-handling