handling.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package endpoint
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "time"
  7. "github.com/go-chi/chi"
  8. kitlog "github.com/go-kit/kit/log"
  9. shipping "github.com/longjoy/micro-go-course/section19/cargo/model"
  10. "github.com/longjoy/micro-go-course/section19/cargo/service/handling"
  11. )
  12. type handlingHandler struct {
  13. s handling.Service
  14. logger kitlog.Logger
  15. }
  16. func (h *handlingHandler) router() chi.Router {
  17. r := chi.NewRouter()
  18. r.Post("/incidents", h.registerIncident)
  19. r.Method("GET", "/docs", http.StripPrefix("/handling/v1/docs", http.FileServer(http.Dir("handling/docs"))))
  20. return r
  21. }
  22. func (h *handlingHandler) registerIncident(w http.ResponseWriter, r *http.Request) {
  23. ctx := context.Background()
  24. var request struct {
  25. CompletionTime time.Time `json:"completion_time"`
  26. TrackingID string `json:"tracking_id"`
  27. VoyageNumber string `json:"voyage"`
  28. Location string `json:"location"`
  29. EventType string `json:"event_type"`
  30. }
  31. if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
  32. h.logger.Log("error", err)
  33. encodeError(ctx, err, w)
  34. return
  35. }
  36. _, err := h.s.RegisterHandlingEvent(
  37. request.CompletionTime,
  38. shipping.TrackingID(request.TrackingID),
  39. shipping.VoyageNumber(request.VoyageNumber),
  40. shipping.UNLocode(request.Location),
  41. stringToEventType(request.EventType),
  42. )
  43. if err != nil {
  44. encodeError(ctx, err, w)
  45. return
  46. }
  47. }
  48. func stringToEventType(s string) shipping.HandlingEventType {
  49. types := map[string]shipping.HandlingEventType{
  50. shipping.Receive.String(): shipping.Receive,
  51. shipping.Load.String(): shipping.Load,
  52. shipping.Unload.String(): shipping.Unload,
  53. shipping.Customs.String(): shipping.Customs,
  54. shipping.Claim.String(): shipping.Claim,
  55. }
  56. return types[s]
  57. }