2016-08-13 11:03:03 +02:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/astaxie/session"
|
2016-08-16 08:30:02 +02:00
|
|
|
"github.com/julienschmidt/httprouter"
|
2016-08-13 11:03:03 +02:00
|
|
|
)
|
|
|
|
|
2016-08-16 08:30:02 +02:00
|
|
|
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"`
|
|
|
|
}
|
|
|
|
|
2016-08-13 11:03:03 +02:00
|
|
|
type JsonResult struct {
|
2016-08-16 08:30:02 +02:00
|
|
|
Data interface{} `json:"data"`
|
|
|
|
Error *ErrorResult `json:"error,omitemty"`
|
2016-08-13 11:03:03 +02:00
|
|
|
Session struct {
|
|
|
|
Login interface{} `json:"login"`
|
|
|
|
Profil map[string]interface{} `json:"profil"`
|
|
|
|
} `json:"session"`
|
|
|
|
}
|
|
|
|
|
2016-08-16 08:30:02 +02:00
|
|
|
func JsonOutput(w http.ResponseWriter, r *http.Request, sess session.Session, data interface{}, errorresult *ErrorResult) {
|
|
|
|
result := JsonResult{Data: data, Error: errorresult}
|
2016-08-13 11:03:03 +02:00
|
|
|
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)
|
|
|
|
}
|
2016-08-16 08:30:02 +02:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|