Переглянути джерело

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

master
sp 4 роки тому
джерело
коміт
32aede562a
4 змінених файлів з 102 додано та 8 видалено
  1. +86
    -3
      apiv1.go
  2. +1
    -1
      config.json
  3. +4
    -2
      debug.go
  4. +11
    -2
      main.go

+ 86
- 3
apiv1.go Переглянути файл

@@ -1,18 +1,101 @@
package main

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

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) {
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 Переглянути файл

@@ -1,5 +1,5 @@
{
"Host":"localhost",
"Host":"0.0.0.0",
"Port":"8080",
"Static": [
{

+ 4
- 2
debug.go Переглянути файл

@@ -5,10 +5,12 @@ import (
log "github.com/sirupsen/logrus"
)

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

+ 11
- 2
main.go Переглянути файл

@@ -7,6 +7,13 @@ import (
"net/http"
)

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

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

func main() {

err := config.readConfig() //wechat API config
@@ -32,8 +39,10 @@ func setupRootFileServer() {
}

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.Fatal(http.ListenAndServe(config.Host+":"+config.Port, nil))

Завантаження…
Відмінити
Зберегти