sum7/warehost
sum7
/
warehost
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
warehost/lib/api/main.go

52 lines
1.6 KiB
Go

package api
import (
"encoding/json"
"net/http"
"github.com/astaxie/session"
"github.com/julienschmidt/httprouter"
)
type Handle func(w http.ResponseWriter, r *http.Request, ps httprouter.Params, sess session.Session) (interface{}, *ErrorResult)
type ErrorResult struct {
Fields []string `json:"fields"`
Message string `json:"msg"`
}
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"`
}
func JsonOutput(w http.ResponseWriter, r *http.Request, sess session.Session, data interface{}, errorresult *ErrorResult) {
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)
}
func SessionHandler(h Handle, sessions *session.Manager) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
sess := sessions.SessionStart(w, r)
data, err := h(w, r, ps, sess)
JsonOutput(w, r, sess, data, err)
}
}