Procházet zdrojové kódy

generalized api response with Envelop and Body, passed first test case suite

master
sp před 4 roky
rodič
revize
32aede562a
4 změnil soubory, kde provedl 102 přidání a 8 odebrání
  1. +86
    -3
      apiv1.go
  2. +1
    -1
      config.json
  3. +4
    -2
      debug.go
  4. +11
    -2
      main.go

+ 86
- 3
apiv1.go Zobrazit soubor

package main package main


import ( import (
"biukop.com/sfm/loan"
"encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
"strings"
"time"
) )


const apiV1Prefix = "/api/v1/" const apiV1Prefix = "/api/v1/"


//apiV1Main version 1 main entry for all wechat callbacks
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 {
apiV1Envelop
Body interface{}
}

var apiV1Handler = []apiV1HandlerMap{
{"POST", "login", apiV1Login},
{"GET", "login", dummyHandler},
}

//apiV1Main version 1 main entry for all REST API
// //
func apiV1Main(w http.ResponseWriter, r *http.Request) { func apiV1Main(w http.ResponseWriter, r *http.Request) {
logRequestDebug(httputil.DumpRequest(r, true)) 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
apiV1Error(w, r)
}

func apiV1Login(w http.ResponseWriter, r *http.Request) {
p := loan.User{}
p.FakeNew()

res := apiV1Response{}
res.apiV1Envelop = apiV1EnvelopBlank()
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 {
apiV1Error(w, nil)
}
}

func apiV1Error(w http.ResponseWriter, r *http.Request) {
dump := logRequestDebug(httputil.DumpRequest(r, true))
msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
dumpLines := strings.Split(dump, "\r\n")
ar := apiV1ResponseBlank()
ar.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
}


path := r.URL.Path[len(apiV1Prefix):]
fmt.Fprintf(w, "Protocol = %s, path= %s \n", r.Method, path)
func apiV1ResponseBlank() (ret apiV1Response) {
ret.apiV1Envelop = apiV1EnvelopBlank()
return
} }

+ 1
- 1
config.json Zobrazit soubor

{ {
"Host":"localhost",
"Host":"0.0.0.0",
"Port":"8080", "Port":"8080",
"Static": [ "Static": [
{ {

+ 4
- 2
debug.go Zobrazit soubor

log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )


func logRequestDebug(data []byte, err error) {
func logRequestDebug(data []byte, err error) (ret string) {
if err == nil { if err == nil {
fmt.Printf("%s\n\n", string(data))
ret = fmt.Sprintf("%s\n\n", string(data))
fmt.Println(ret)
} else { } else {
log.Fatalf("%s\n\n", err) log.Fatalf("%s\n\n", err)
} }
return
} }

+ 11
- 2
main.go Zobrazit soubor

"net/http" "net/http"
) )


type httpEntry func(http.ResponseWriter, *http.Request)

var httpEntryMap = map[string]httpEntry{
apiV1Prefix: apiV1Main,
"/dummy/": dummyHandler,
}

func main() { func main() {


err := config.readConfig() //wechat API config err := config.readConfig() //wechat API config
} }


func setupHTTPHandler() { func setupHTTPHandler() {
http.HandleFunc(apiV1Prefix, apiV1Main)
http.HandleFunc("/dummy/", dummyHandler)

for key, val := range httpEntryMap {
http.HandleFunc(key, val)
}


log.Printf("Server started at %s:%s\n", config.Host, config.Port) log.Printf("Server started at %s:%s\n", config.Host, config.Port)
log.Fatal(http.ListenAndServe(config.Host+":"+config.Port, nil)) log.Fatal(http.ListenAndServe(config.Host+":"+config.Port, nil))

Načítá se…
Zrušit
Uložit