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

58 lines
1.8 KiB
Go
Raw Normal View History

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-09-03 10:18:46 +02:00
// Handle for session
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)
2016-09-03 10:18:46 +02:00
// ErrorResult struct for api error answer
2016-08-16 08:30:02 +02:00
type ErrorResult struct {
Fields []string `json:"fields"`
Message string `json:"msg"`
}
2016-09-03 10:18:46 +02:00
// JSONResult struct for api answer
type JSONResult struct {
2016-08-16 08:30:02 +02:00
Data interface{} `json:"data"`
2016-08-20 01:17:08 +02:00
Error *ErrorResult `json:"error,omitempty"`
2016-08-13 11:03:03 +02:00
Session struct {
2016-08-20 01:17:08 +02:00
Login interface{} `json:"login,omitempty"`
Profil map[string]interface{} `json:"profil,omitempty"`
} `json:"session,omitempty"`
2016-08-13 11:03:03 +02:00
}
2016-09-03 10:18:46 +02:00
// JSONOutput generate default json answer
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
2016-09-03 10:18:46 +02:00
// SessionHandler Handler to manage session of api request
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)
2016-09-03 10:18:46 +02:00
JSONOutput(w, r, sess, data, err)
2016-08-16 08:30:02 +02:00
}
}