1package main2 3import (4 "encoding/json"5 "fmt"6 "net/http"7)8 9type Order struct {10 Payload string11}12 13type Outcome struct {14 Done bool15}16 17type usecase interface {18 Place(order Order) (Outcome, error)19}20 21type reqBody struct {22 Payload string `json:"payload"`23}24 25type respBody struct {26 Message string `json:"message"`27 Error string `json:"error,omitempty"`28}29 30type Handler struct {31 uc usecase32}33 34func NewHandler(uc usecase) *Handler {35 return &Handler{uc: uc}36}37 38func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {39 if r.Method != http.MethodPost {40 w.WriteHeader(http.StatusMethodNotAllowed)41 _ = json.NewEncoder(w).Encode(respBody{42 Error: fmt.Sprintf("method %s not allowed", r.Method),43 })44 return45 }46 47 w.Header().Set("Content-Type", "application/json")48 49 var body reqBody50 if e := json.NewDecoder(r.Body).Decode(&body); e != nil {51 w.WriteHeader(http.StatusBadRequest)52 _ = json.NewEncoder(w).Encode(respBody{53 Error: fmt.Sprintf("failed to decode request: %v", e),54 })55 return56 }57 58 if body.Payload == "" {59 w.WriteHeader(http.StatusBadRequest)60 _ = json.NewEncoder(w).Encode(respBody{61 Error: "payload is required",62 })63 return64 }65 66 _, e := h.uc.Place(Order{Payload: body.Payload})67 if e != nil {68 w.WriteHeader(http.StatusInternalServerError)69 _ = json.NewEncoder(w).Encode(respBody{70 Error: fmt.Sprintf("failed to process request: %v", e),71 })72 return73 }74 75 w.WriteHeader(http.StatusOK)76 _ = json.NewEncoder(w).Encode(respBody{77 Message: "request processed successfully",78 })79}