http.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package transport
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/go-kit/kit/log"
  8. "github.com/go-kit/kit/transport"
  9. kithttp "github.com/go-kit/kit/transport/http"
  10. "github.com/gorilla/mux"
  11. "github.com/longjoy/micro-go-course/section19/cargo/endpoint"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. )
  16. var (
  17. ErrorBadRequest = errors.New("invalid request parameter")
  18. )
  19. // MakeHttpHandler make http handler use mux
  20. func MakeHttpHandler(ctx context.Context, endpoints *endpoint.CargoEndpoints) http.Handler {
  21. r := mux.NewRouter()
  22. kitLog := log.NewLogfmtLogger(os.Stderr)
  23. kitLog = log.With(kitLog, "ts", log.DefaultTimestampUTC)
  24. kitLog = log.With(kitLog, "caller", log.DefaultCaller)
  25. options := []kithttp.ServerOption{
  26. kithttp.ServerErrorHandler(transport.NewLogErrorHandler(kitLog)),
  27. kithttp.ServerErrorEncoder(encodeError),
  28. }
  29. r.Methods("GET").Path("/locations").Handler(kithttp.NewServer(
  30. endpoints.LocationsEndpoint,
  31. decodeLocationsRequest,
  32. encodeJSONResponse,
  33. options...,
  34. ))
  35. r.Methods("POST").Path("/incidents").Handler(kithttp.NewServer(
  36. endpoints.RegisterHandlingEventEndpoint,
  37. decodeRegisterHandlingEventRequest,
  38. encodeJSONResponse,
  39. options...,
  40. ))
  41. r.Methods("POST").PathPrefix("/cargos").Path("/").Handler(kithttp.NewServer(
  42. endpoints.LoadCargoEndpoint,
  43. decodeLoadCargoRequest,
  44. encodeJSONResponse,
  45. options...,
  46. ))
  47. r.Methods("POST").PathPrefix("/cargos").Path("/change_destination").Handler(kithttp.NewServer(
  48. endpoints.ChangeDestinationEndpoint,
  49. decodeChangeDestinationRequest,
  50. encodeJSONResponse,
  51. options...,
  52. ))
  53. r.Methods("POST").PathPrefix("/cargos").Path("/").Handler(kithttp.NewServer(
  54. endpoints.AssignCargoToRouteEndpoint,
  55. decodeAssignCargoToRouteRequest,
  56. encodeJSONResponse,
  57. options...,
  58. ))
  59. r.Methods("POST").PathPrefix("/cargos").Path("/assign_to_route").Handler(kithttp.NewServer(
  60. endpoints.BookCargoEndpoint,
  61. decodeBookCargoRequest,
  62. encodeJSONResponse,
  63. options...,
  64. ))
  65. return r
  66. }
  67. // decodeHealthCheckRequest decode request
  68. func decodeLocationsRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  69. return endpoint.LocationsRequest{}, nil
  70. }
  71. func decodeBookCargoRequest(_ context.Context, r *http.Request) (interface{}, error) {
  72. body, err := ioutil.ReadAll(r.Body)
  73. if err != nil {
  74. fmt.Printf("read body err, %v\n", err)
  75. return nil, err
  76. }
  77. println("json:", string(body))
  78. var bcr endpoint.BookCargoRequest
  79. if err = json.Unmarshal(body, &bcr); err != nil {
  80. fmt.Printf("Unmarshal err, %v\n", err)
  81. return nil, err
  82. }
  83. fmt.Printf("%+v", bcr)
  84. return &endpoint.BookCargoRequest{
  85. Origin: bcr.Origin,
  86. Destination: bcr.Destination,
  87. Deadline: bcr.Deadline,
  88. }, nil
  89. }
  90. func decodeAssignCargoToRouteRequest(_ context.Context, r *http.Request) (interface{}, error) {
  91. body, err := ioutil.ReadAll(r.Body)
  92. if err != nil {
  93. fmt.Printf("read body err, %v\n", err)
  94. return nil, err
  95. }
  96. println("json:", string(body))
  97. var acr endpoint.AssignCargoToRouteRequest
  98. if err = json.Unmarshal(body, &acr); err != nil {
  99. fmt.Printf("Unmarshal err, %v\n", err)
  100. return nil, err
  101. }
  102. fmt.Printf("%+v", acr)
  103. return &endpoint.AssignCargoToRouteRequest{
  104. Id: acr.Id,
  105. Itinerary: acr.Itinerary,
  106. }, nil
  107. }
  108. func decodeLoadCargoRequest(_ context.Context, r *http.Request) (interface{}, error) {
  109. body, err := ioutil.ReadAll(r.Body)
  110. if err != nil {
  111. fmt.Printf("read body err, %v\n", err)
  112. return nil, err
  113. }
  114. println("json:", string(body))
  115. var lcr endpoint.LoadCargoRequest
  116. if err = json.Unmarshal(body, &lcr); err != nil {
  117. fmt.Printf("Unmarshal err, %v\n", err)
  118. return nil, err
  119. }
  120. fmt.Printf("%+v", lcr)
  121. return &endpoint.LoadCargoRequest{
  122. Id: lcr.Id,
  123. }, nil
  124. }
  125. func decodeChangeDestinationRequest(_ context.Context, r *http.Request) (interface{}, error) {
  126. body, err := ioutil.ReadAll(r.Body)
  127. if err != nil {
  128. fmt.Printf("read body err, %v\n", err)
  129. return nil, err
  130. }
  131. println("json:", string(body))
  132. var cdr endpoint.ChangeDestinationRequest
  133. if err = json.Unmarshal(body, &cdr); err != nil {
  134. fmt.Printf("Unmarshal err, %v\n", err)
  135. return nil, err
  136. }
  137. fmt.Printf("%+v", cdr)
  138. return &endpoint.ChangeDestinationRequest{
  139. Id: cdr.Id,
  140. Destination: cdr.Destination,
  141. }, nil
  142. }
  143. func decodeRegisterHandlingEventRequest(_ context.Context, r *http.Request) (interface{}, error) {
  144. body, err := ioutil.ReadAll(r.Body)
  145. if err != nil {
  146. fmt.Printf("read body err, %v\n", err)
  147. return nil, err
  148. }
  149. println("json:", string(body))
  150. var rhe endpoint.RegisterHandlingEventRequest
  151. if err = json.Unmarshal(body, &rhe); err != nil {
  152. fmt.Printf("Unmarshal err, %v\n", err)
  153. return nil, err
  154. }
  155. fmt.Printf("%+v", rhe)
  156. return &endpoint.RegisterHandlingEventRequest{
  157. Id: rhe.Id,
  158. Completed: rhe.Completed,
  159. VoyageNumber: rhe.VoyageNumber,
  160. UnLocode: rhe.UnLocode,
  161. EventType: rhe.EventType,
  162. }, nil
  163. }
  164. func encodeJSONResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  165. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  166. return json.NewEncoder(w).Encode(response)
  167. }
  168. func encodeError(_ context.Context, err error, w http.ResponseWriter) {
  169. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  170. switch err {
  171. default:
  172. w.WriteHeader(http.StatusInternalServerError)
  173. }
  174. json.NewEncoder(w).Encode(map[string]interface{}{
  175. "error": err.Error(),
  176. })
  177. }