go get github.com/codimite/gomite
funcmain(){
gm:= gomite.Gomite{Port: "8080", Handler: AppRecoverHandler(GlobalHandler{})}
gomite.InitTemplates([]string{"templates"})
// Endpointgm.HandleFunc("/getting-started", func(rw http.ResponseWriter, req*http.Request) {
rw.WriteHeader(200)
rw.Write([]byte("Health check"))
})
gm.Start() // Start the server
}
// utilstypeGlobalHandlerstruct {}
funcAppRecoverHandler(handler http.Handler) http.Handler {
returnhttp.HandlerFunc(func(rw http.ResponseWriter, r*http.Request) {
deferfunc() {
r:=recover()
ifr!=nil {
AppLogger{}.Error("[Critical Error Occured]", "AppRecoverHandler", r)
varmessagestruct {
Messagestring`json:"message,omitempty"`
}
message.Message="Something Went Wrong"rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(rw).Encode(message)
return
}
}()
handler.ServeHTTP(rw, r)
})
}AppRecoverHandler - Handle panics & stop program from exiting
import(
"github.com/codimite/gomite"
interceptor "github.com/codimite/gomite/interceptors"
)
funcmain(){
headerInterceptor:= interceptor.MiddlewareChain{HeaderCheck()}
gm:= gomite.Gomite{Port: servePort, Handler: AppRecoverHandler(GlobalHandler{})}
gomite.InitTemplates([]string{"templates"})
gm.Handle("/header-check", headerInterceptor.Handler(HeaderCheckHandler))
}
...funcHeaderCheck() interceptor.MiddlewareInterceptor {
returnfunc(rw http.ResponseWriter, req*http.Request, next http.HandlerFunc) {
reqHeader:=req.Header.Get("X-Test-Header")
ifreqHeader!="X-Test-Header-Value" {
http.Error(rw, "Not Authorized", http.StatusUnauthorized)
return
}
next(rw, req)
}
}funcHeaderCheckHandler(rw http.ResponseWriter, req*http.Request) {
rw.WriteHeader(200)
rw.Write([]byte("ok"))
return
}gm.Start(WithReadTimeout(20*time.Second))