github.com/seeker-insurance/kit@v0.0.13/web/server/echo.go (about) 1 package server 2 3 import ( 4 "fmt" 5 6 valid "github.com/asaskevich/govalidator" 7 "github.com/seeker-insurance/kit/web" 8 "github.com/facebookgo/grace/gracehttp" 9 "github.com/labstack/echo" 10 "github.com/labstack/echo/middleware" 11 "github.com/spf13/viper" 12 ) 13 14 type apiValidator struct{} 15 16 func (v *apiValidator) Validate(i interface{}) error { 17 _, err := valid.ValidateStruct(i) 18 return err 19 } 20 21 var ( 22 Echo *echo.Echo 23 mws = []echo.MiddlewareFunc{} 24 host string 25 ) 26 27 func NewEcho(port int) *echo.Echo { 28 e := echo.New() 29 e.Validator = &apiValidator{} 30 e.Server.Addr = fmt.Sprintf(":%v", port) 31 e.HTTPErrorHandler = web.ErrorHandler 32 33 e.Use(web.ApiContextMiddleWare()) 34 e.Use(middleware.Logger()) 35 e.Use(middleware.Recover()) 36 e.Use(middleware.JWTWithConfig(middleware.JWTConfig{ 37 Skipper: web.AuthedSkipper(), 38 SigningKey: []byte(viper.GetString("secret")), 39 })) 40 e.Use(mws...) 41 42 return e 43 } 44 45 func Start(port int, h string) { 46 Echo = NewEcho(port) 47 web.InitRoutes(Echo) 48 host = h 49 50 Echo.Logger.Fatal(gracehttp.Serve(Echo.Server)) 51 } 52 53 func URI(routeName string, args ...interface{}) (string, error) { 54 path := Echo.Reverse(routeName, args...) 55 if path == "" { 56 return "", fmt.Errorf("Cannot form URI, route name '%v' not found", routeName) 57 } 58 59 if host == "" { 60 return "", fmt.Errorf("Cannot form URI, host not set. (use --host or env to set one)") 61 } 62 63 return host + path, nil 64 } 65 66 func AddValidator(name string, f valid.CustomTypeValidator) { 67 valid.CustomTypeTagMap.Set("score", f) 68 } 69 70 func AddMiddleWare(mw echo.MiddlewareFunc) { 71 mws = append(mws, mw) 72 }