From ad8e9dd2af2320b920444b98a0d71d8c0a565734 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Tikvi=C4=87?= Date: Thu, 26 Apr 2018 12:29:06 +0200 Subject: [PATCH] added middleware and functions to support getting default values from nil interfaces --- default_values.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ http.go | 10 +++++----- json.go | 16 ++++------------ localization.go | 4 ++-- main.go | 22 ++++++++++++++++++++++ middleware.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 130 insertions(+), 19 deletions(-) create mode 100644 default_values.go create mode 100644 main.go create mode 100644 middleware.go diff --git a/default_values.go b/default_values.go new file mode 100644 index 0000000..36ae0bb --- /dev/null +++ b/default_values.go @@ -0,0 +1,50 @@ +package webutility + +func Int32ValueOrDefault(val *interface{}) (def int32) { + if *val != nil { + def = (*val).(int32) + } + return def +} + +func Int64ValueOrDefault(val *interface{}) (def int64) { + if *val != nil { + def = (*val).(int64) + } + return def +} + +func Uint32ValueOrDefault(val *interface{}) (def uint32) { + if *val != nil { + def = (*val).(uint32) + } + return def +} + +func Uint64ValueOrDefault(val *interface{}) (def uint64) { + if *val != nil { + def = (*val).(uint64) + } + return def +} + +func Float32ValueOrDefault(val *interface{}) (def float32) { + if *val != nil { + def = (*val).(float32) + } + return def +} + +func Float64ValueOrDefault(val *interface{}) (def float64) { + if *val != nil { + return (*val).(float64) + } + return def +} + +func StringValueOrDefault(val *interface{}) (def string) { + if *val != nil { + def = (*val).(string) + } + return def +} diff --git a/http.go b/http.go index 07a79ab..482aac0 100644 --- a/http.go +++ b/http.go @@ -2,6 +2,7 @@ package webutility import ( "encoding/json" + "fmt" "net/http" ) @@ -10,21 +11,20 @@ type webError struct { Error string `json:"error"` } -// NotFoundHandler writes HTTP error 404 to w. -func NotFoundHandler(w http.ResponseWriter, req *http.Request) { +// NotFoundHandlerFunc writes HTTP error 404 to w. +func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) { SetDefaultHeaders(w) if req.Method == "OPTIONS" { return } - NotFound(w, req, "Not found") + NotFound(w, req, fmt.Sprintf("Resource you requested was not found: %s", req.URL.String())) } // SetDefaultHeaders set's default headers for an HTTP response. func SetDefaultHeaders(w http.ResponseWriter) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", `Accept, Content-Type, - Content-Length, Accept-Encoding, X-CSRF-Token, Authorization`) + w.Header().Set("Access-Control-Allow-Headers", `Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization`) w.Header().Set("Content-Type", "application/json; charset=utf-8") } diff --git a/json.go b/json.go index f9b88f0..24699b1 100644 --- a/json.go +++ b/json.go @@ -9,8 +9,6 @@ import ( "net/http" "sync" "time" - - "git.to-net.rs/marko.tikvic/gologger" ) var ( @@ -25,16 +23,6 @@ var ( driver string ) -var logger *gologger.Logger - -func init() { - var err error - logger, err = gologger.New("webutility", gologger.MaxLogSize100KB) - if err != nil { - fmt.Printf("webutility: %s\n", err.Error()) - } -} - type LangMap map[string]map[string]string type Field struct { @@ -68,6 +56,10 @@ type Payload struct { Data interface{} `json:"data"` } +func (p *Payload) SetData(data interface{}) { + p.Data = data +} + // NewPayload returs a payload sceleton for entity described with etype. func NewPayload(r *http.Request, etype string) Payload { pload := metadata[etype] diff --git a/localization.go b/localization.go index 298f4b9..17ca979 100644 --- a/localization.go +++ b/localization.go @@ -12,8 +12,8 @@ type Dictionary struct { defaultLocale string } -func NewDictionary() Dictionary { - return Dictionary{ +func NewDictionary() *Dictionary { + return &Dictionary{ locales: map[string]map[string]string{}, } } diff --git a/main.go b/main.go new file mode 100644 index 0000000..761af13 --- /dev/null +++ b/main.go @@ -0,0 +1,22 @@ +package webutility + +import ( + "fmt" + + "git.to-net.rs/marko.tikvic/gologger" +) + +var logger *gologger.Logger +var reqLogger *gologger.Logger + +func init() { + var err error + logger, err = gologger.New("metadata", gologger.MaxLogSize100KB) + if err != nil { + fmt.Printf("webutility: %s\n", err.Error()) + } + reqLogger, err = gologger.New("http", gologger.MaxLogSize5MB) + if err != nil { + fmt.Printf("webutility: %s\n", err.Error()) + } +} diff --git a/middleware.go b/middleware.go new file mode 100644 index 0000000..c56060b --- /dev/null +++ b/middleware.go @@ -0,0 +1,47 @@ +package webutility + +import ( + "net/http" + "time" +) + +func WithSetHeaders(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + SetDefaultHeaders(w) + if req.Method == http.MethodOptions { + return + } + h.ServeHTTP(w, req) + }) +} + +func WithParseForm(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + err := req.ParseForm() + if err != nil { + BadRequest(w, req, err.Error()) + return + } + h.ServeHTTP(w, req) + }) +} + +func WithLog(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + reqLogger.LogRequest(req, "") + t1 := time.Now() + h.ServeHTTP(w, req) + t2 := time.Now() + reqLogger.LogResponse(w, t2.Sub(t1)) + }) +} + +func WithAuth(h http.Handler, authorizedRoles []string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if _, ok := AuthCheck(req, authorizedRoles); !ok { + Unauthorized(w, req, "") + return + } + h.ServeHTTP(w, req) + }) +} -- 1.8.1.2