Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

102 lignes
2.0KB

  1. package main
  2. import (
  3. "biukop.com/sfm/loan"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/http/httputil"
  8. "strings"
  9. "time"
  10. )
  11. const apiV1Prefix = "/api/v1/"
  12. type apiV1HandlerMap struct {
  13. Method string
  14. Path string //regex
  15. Handler func(http.ResponseWriter, *http.Request)
  16. }
  17. type apiV1Envelop struct {
  18. Version string
  19. Success bool
  20. Msg string
  21. TimeStamp string
  22. }
  23. type apiV1Response struct {
  24. Env apiV1Envelop
  25. Body interface{}
  26. }
  27. var apiV1Handler = []apiV1HandlerMap{
  28. {"POST", "login", apiV1Login},
  29. {"GET", "login", apiV1DumpRequest},
  30. }
  31. //apiV1Main version 1 main entry for all REST API
  32. //
  33. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  34. logRequestDebug(httputil.DumpRequest(r, true))
  35. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  36. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  37. for _, node := range apiV1Handler {
  38. if r.Method == node.Method && path == node.Path {
  39. node.Handler(w, r)
  40. return
  41. }
  42. }
  43. //Catch for all
  44. apiV1DumpRequest(w, r)
  45. }
  46. func apiV1Login(w http.ResponseWriter, r *http.Request) {
  47. p := loan.User{}
  48. p.FakeNew()
  49. res := apiV1ResponseBlank()
  50. res.Body = p
  51. apiSendJson(res, w)
  52. }
  53. func apiSendJson(p interface{}, w http.ResponseWriter) {
  54. b, e := json.Marshal(p)
  55. w.Header().Set("Content-Type", "text/json; charset=utf-8")
  56. if e == nil {
  57. fmt.Fprint(w, string(b))
  58. } else {
  59. apiV1DumpRequest(w, nil)
  60. }
  61. }
  62. func apiV1DumpRequest(w http.ResponseWriter, r *http.Request) {
  63. dump := logRequestDebug(httputil.DumpRequest(r, true))
  64. dump = strings.TrimSpace(dump)
  65. msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  66. dumpLines := strings.Split(dump, "\r\n")
  67. ar := apiV1ResponseBlank()
  68. ar.Env.Msg = msg
  69. ar.Body = dumpLines
  70. b, _ := json.Marshal(ar)
  71. fmt.Fprintf(w, "%s\n", b)
  72. }
  73. func apiV1EnvelopBlank() (ret apiV1Envelop) {
  74. ts := time.Now().Format("2006-01-02 15:04:05")
  75. ret = apiV1Envelop{
  76. Version: loan.Version,
  77. Success: true,
  78. Msg: "",
  79. TimeStamp: ts,
  80. }
  81. return
  82. }
  83. func apiV1ResponseBlank() (ret apiV1Response) {
  84. ret.Env = apiV1EnvelopBlank()
  85. return
  86. }