9 "github.com/gorilla/mux"
11 kitlog "github.com/go-kit/kit/log"
12 kithttp "github.com/go-kit/kit/transport/http"
14 "github.com/go-kit/kit/examples/shipping/cargo"
15 "github.com/go-kit/kit/examples/shipping/location"
16 "github.com/go-kit/kit/examples/shipping/voyage"
19 // MakeHandler returns a handler for the handling service.
20 func MakeHandler(hs Service, logger kitlog.Logger) http.Handler {
23 opts := []kithttp.ServerOption{
24 kithttp.ServerErrorLogger(logger),
25 kithttp.ServerErrorEncoder(encodeError),
28 registerIncidentHandler := kithttp.NewServer(
29 makeRegisterIncidentEndpoint(hs),
30 decodeRegisterIncidentRequest,
35 r.Handle("/handling/v1/incidents", registerIncidentHandler).Methods("POST")
40 func decodeRegisterIncidentRequest(_ context.Context, r *http.Request) (interface{}, error) {
42 CompletionTime time.Time `json:"completion_time"`
43 TrackingID string `json:"tracking_id"`
44 VoyageNumber string `json:"voyage"`
45 Location string `json:"location"`
46 EventType string `json:"event_type"`
49 if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
53 return registerIncidentRequest{
54 CompletionTime: body.CompletionTime,
55 ID: cargo.TrackingID(body.TrackingID),
56 Voyage: voyage.Number(body.VoyageNumber),
57 Location: location.UNLocode(body.Location),
58 EventType: stringToEventType(body.EventType),
62 func stringToEventType(s string) cargo.HandlingEventType {
63 types := map[string]cargo.HandlingEventType{
64 cargo.Receive.String(): cargo.Receive,
65 cargo.Load.String(): cargo.Load,
66 cargo.Unload.String(): cargo.Unload,
67 cargo.Customs.String(): cargo.Customs,
68 cargo.Claim.String(): cargo.Claim,
73 func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
74 if e, ok := response.(errorer); ok && e.error() != nil {
75 encodeError(ctx, e.error(), w)
78 w.Header().Set("Content-Type", "application/json; charset=utf-8")
79 return json.NewEncoder(w).Encode(response)
82 type errorer interface {
86 // encode errors from business-logic
87 func encodeError(_ context.Context, err error, w http.ResponseWriter) {
88 w.Header().Set("Content-Type", "application/json; charset=utf-8")
90 case cargo.ErrUnknown:
91 w.WriteHeader(http.StatusNotFound)
92 case ErrInvalidArgument:
93 w.WriteHeader(http.StatusBadRequest)
95 w.WriteHeader(http.StatusInternalServerError)
97 json.NewEncoder(w).Encode(map[string]interface{}{