Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

106 lines
2.1KB

  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. Ext interface{}
  27. Map map[string]interface{}
  28. }
  29. var apiV1Handler = []apiV1HandlerMap{
  30. {"POST", "login", apiV1Login},
  31. {"GET", "login", apiV1DumpRequest},
  32. }
  33. //apiV1Main version 1 main entry for all REST API
  34. //
  35. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  36. logRequestDebug(httputil.DumpRequest(r, true))
  37. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  38. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  39. for _, node := range apiV1Handler {
  40. if r.Method == node.Method && path == node.Path {
  41. node.Handler(w, r)
  42. return
  43. }
  44. }
  45. //Catch for all
  46. apiV1DumpRequest(w, r)
  47. }
  48. func apiV1Login(w http.ResponseWriter, r *http.Request) {
  49. p := loan.User{}
  50. p.FakeNew()
  51. res := apiV1ResponseBlank()
  52. res.Body = p
  53. res.Map["some"] = p
  54. apiSendJson(res, w)
  55. }
  56. func apiSendJson(p interface{}, w http.ResponseWriter) {
  57. b, e := json.Marshal(p)
  58. w.Header().Set("Content-Type", "text/json; charset=utf-8")
  59. if e == nil {
  60. fmt.Fprint(w, string(b))
  61. } else {
  62. apiV1DumpRequest(w, nil)
  63. }
  64. }
  65. func apiV1DumpRequest(w http.ResponseWriter, r *http.Request) {
  66. dump := logRequestDebug(httputil.DumpRequest(r, true))
  67. dump = strings.TrimSpace(dump)
  68. msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  69. dumpLines := strings.Split(dump, "\r\n")
  70. ar := apiV1ResponseBlank()
  71. ar.Env.Msg = msg
  72. ar.Body = dumpLines
  73. b, _ := json.Marshal(ar)
  74. fmt.Fprintf(w, "%s\n", b)
  75. }
  76. func apiV1EnvelopBlank() (ret apiV1Envelop) {
  77. ts := time.Now().Format("2006-01-02 15:04:05")
  78. ret = apiV1Envelop{
  79. Version: loan.Version,
  80. Success: true,
  81. Msg: "",
  82. TimeStamp: ts,
  83. }
  84. return
  85. }
  86. func apiV1ResponseBlank() (ret apiV1Response) {
  87. ret.Env = apiV1EnvelopBlank()
  88. ret.Map = make(map[string]interface{})
  89. return
  90. }