tracking.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package endpoint
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/go-chi/chi"
  6. kitlog "github.com/go-kit/kit/log"
  7. "github.com/longjoy/micro-go-course/section19/cargo/service/tracking"
  8. "net/http"
  9. )
  10. type trackingHandler struct {
  11. s tracking.Service
  12. logger kitlog.Logger
  13. }
  14. func (h *trackingHandler) router() chi.Router {
  15. r := chi.NewRouter()
  16. r.Get("/cargos/{trackingID}", h.track)
  17. r.Method("GET", "/docs", http.StripPrefix("/tracking/v1/docs", http.FileServer(http.Dir("tracking/docs"))))
  18. return r
  19. }
  20. func (h *trackingHandler) track(w http.ResponseWriter, r *http.Request) {
  21. ctx := context.Background()
  22. trackingID := chi.URLParam(r, "trackingID")
  23. c, err := h.s.Track(trackingID)
  24. if err != nil {
  25. encodeError(ctx, err, w)
  26. return
  27. }
  28. var response = struct {
  29. Cargo *tracking.Cargo `json:"cargo"`
  30. }{Cargo: &c}
  31. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  32. if err := json.NewEncoder(w).Encode(response); err != nil {
  33. h.logger.Log("error", err)
  34. encodeError(ctx, err, w)
  35. return
  36. }
  37. }