|
- package main
-
- import (
- "biukop.com/sfm/loan"
- "encoding/json"
- "fmt"
- "net/http"
- "net/http/httputil"
- "strings"
- "time"
- )
-
- const apiV1Prefix = "/api/v1/"
-
- type apiV1HandlerMap struct {
- Method string
- Path string //regex
- Handler func(http.ResponseWriter, *http.Request)
- }
-
- type apiV1Envelop struct {
- Version string
- Success bool
- Msg string
- TimeStamp string
- }
-
- type apiV1Response struct {
- Env apiV1Envelop
- Body interface{}
- }
-
- var apiV1Handler = []apiV1HandlerMap{
- {"POST", "login", apiV1Login},
- {"GET", "login", apiV1DumpRequest},
- }
-
- //apiV1Main version 1 main entry for all REST API
- //
- func apiV1Main(w http.ResponseWriter, r *http.Request) {
- logRequestDebug(httputil.DumpRequest(r, true))
- w.Header().Set("Content-Type", "application/json;charset=UTF-8")
- path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
-
- for _, node := range apiV1Handler {
- if r.Method == node.Method && path == node.Path {
- node.Handler(w, r)
- return
- }
- }
- //Catch for all
- apiV1DumpRequest(w, r)
- }
-
- func apiV1Login(w http.ResponseWriter, r *http.Request) {
- p := loan.User{}
- p.FakeNew()
-
- res := apiV1ResponseBlank()
- res.Body = p
- apiSendJson(res, w)
-
- }
-
- func apiSendJson(p interface{}, w http.ResponseWriter) {
- b, e := json.Marshal(p)
- w.Header().Set("Content-Type", "text/json; charset=utf-8")
- if e == nil {
- fmt.Fprint(w, string(b))
- } else {
- apiV1DumpRequest(w, nil)
- }
- }
-
- func apiV1DumpRequest(w http.ResponseWriter, r *http.Request) {
- dump := logRequestDebug(httputil.DumpRequest(r, true))
- dump = strings.TrimSpace(dump)
- msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
- dumpLines := strings.Split(dump, "\r\n")
- ar := apiV1ResponseBlank()
- ar.Env.Msg = msg
- ar.Body = dumpLines
- b, _ := json.Marshal(ar)
- fmt.Fprintf(w, "%s\n", b)
- }
-
- func apiV1EnvelopBlank() (ret apiV1Envelop) {
- ts := time.Now().Format("2006-01-02 15:04:05")
- ret = apiV1Envelop{
- Version: loan.Version,
- Success: true,
- Msg: "",
- TimeStamp: ts,
- }
- return
- }
-
- func apiV1ResponseBlank() (ret apiV1Response) {
- ret.Env = apiV1EnvelopBlank()
- return
- }
|