package api import ( "context" "encoding/json" "net/http" log "github.com/sirupsen/logrus" // TODO-Bad libsession "dev.sum7.eu/sum7/warehost/lib/session" ) // Handle with response type Handle func(w http.ResponseWriter, r *http.Request) // ErrorResult struct for api error answer type ErrorResult struct { Fields []string `json:"fields"` Message string `json:"msg"` } // JSONResult struct for api answer type JSONResult struct { Data interface{} `json:"data"` Error *ErrorResult `json:"error,omitempty"` Session struct { Login interface{} `json:"login,omitempty"` Profil map[string]interface{} `json:"profil,omitempty"` } `json:"session,omitempty"` } // SessionHandler Handler to manage session of api request func SessionHandler(h Handle) Handle { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() sess := libsession.SessionStart(w, r) ctx = context.WithValue(ctx, "session", sess) r = r.WithContext(ctx) h(w, r) } } // JSONWrite generate default json answer func JSONWrite(w http.ResponseWriter, r *http.Request, data interface{}, errorresult *ErrorResult) { ctx := r.Context() sess := ctx.Value("session").(libsession.Session) result := JSONResult{Data: data, Error: errorresult} result.Session.Login = sess.Get("login") js, err := json.Marshal(result) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) } w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") w.Header().Set("Access-Control-Allow-Credentials", "true") w.Write(js) } //JSONDecoder handle complete request of JSON func JSONDecoder(w http.ResponseWriter, r *http.Request, logger *log.Entry, data interface{}) (returnerr *ErrorResult) { /*if r.Header.Get("Content-Type") != "application/json" { logger.Error("fetch wrong request type") returnerr = &ErrorResult{ Message: "Internal Request Error", } w.WriteHeader(http.StatusBadRequest) return } */ err := json.NewDecoder(r.Body).Decode(data) if err != nil { logger.Error("fetch request") returnerr = &ErrorResult{ Message: "Internal Request Error", } w.WriteHeader(http.StatusBadRequest) return } return nil }