http.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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/section25/goods/endpoint"
  12. "net/http"
  13. "os"
  14. )
  15. var (
  16. ErrorBadRequest = errors.New("invalid request parameter")
  17. )
  18. // MakeHttpHandler make http handler use mux
  19. func MakeHttpHandler(ctx context.Context, endpoints *endpoint.GoodsEndpoints) http.Handler {
  20. r := mux.NewRouter()
  21. kitLog := log.NewLogfmtLogger(os.Stderr)
  22. kitLog = log.With(kitLog, "ts", log.DefaultTimestampUTC)
  23. kitLog = log.With(kitLog, "caller", log.DefaultCaller)
  24. options := []kithttp.ServerOption{
  25. kithttp.ServerErrorHandler(transport.NewLogErrorHandler(kitLog)),
  26. kithttp.ServerErrorEncoder(encodeError),
  27. }
  28. r.Methods("GET").Path("/goods/detail").Handler(kithttp.NewServer(
  29. endpoints.GoodsDetailEndpoint,
  30. decodeGoodsDetailRequest,
  31. encodeJSONResponse,
  32. options...,
  33. ))
  34. return r
  35. }
  36. func decodeGoodsDetailRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  37. id := r.URL.Query().Get("id")
  38. fmt.Print("dfsf")
  39. if id == "" {
  40. return nil, ErrorBadRequest
  41. }
  42. return endpoint.GoodsDetailRequest{
  43. Id: id,
  44. }, nil
  45. }
  46. func encodeJSONResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  47. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  48. return json.NewEncoder(w).Encode(response)
  49. }
  50. func encodeError(_ context.Context, err error, w http.ResponseWriter) {
  51. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  52. switch err {
  53. default:
  54. w.WriteHeader(http.StatusInternalServerError)
  55. }
  56. json.NewEncoder(w).Encode(map[string]interface{}{
  57. "error": err.Error(),
  58. })
  59. }