http.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package transport
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/go-kit/kit/log"
  7. "github.com/go-kit/kit/transport"
  8. kithttp "github.com/go-kit/kit/transport/http"
  9. "github.com/gorilla/mux"
  10. "github.com/longjoy/micro-go-course/section28/comment/endpoint"
  11. "net/http"
  12. "os"
  13. )
  14. var (
  15. ErrorBadRequest = errors.New("invalid request parameter")
  16. )
  17. // MakeHttpHandler make http handler use mux
  18. func MakeHttpHandler(ctx context.Context, endpoints *endpoint.CommentsEndpoints) http.Handler {
  19. r := mux.NewRouter()
  20. kitLog := log.NewLogfmtLogger(os.Stderr)
  21. kitLog = log.With(kitLog, "ts", log.DefaultTimestampUTC)
  22. kitLog = log.With(kitLog, "caller", log.DefaultCaller)
  23. options := []kithttp.ServerOption{
  24. kithttp.ServerErrorHandler(transport.NewLogErrorHandler(kitLog)),
  25. kithttp.ServerErrorEncoder(encodeError),
  26. }
  27. r.Methods("GET").Path("/comments/detail").Handler(kithttp.NewServer(
  28. endpoints.CommentsListEndpoint,
  29. decodeCommentsListRequest,
  30. encodeJSONResponse,
  31. options...,
  32. ))
  33. r.Methods("GET").Path("/health").Handler(kithttp.NewServer(
  34. endpoints.HealthCheckEndpoint,
  35. decodeHealthCheckRequest,
  36. encodeJSONResponse,
  37. options...,
  38. ))
  39. return r
  40. }
  41. func decodeHealthCheckRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  42. return endpoint.HealthRequest{}, nil
  43. }
  44. func decodeCommentsListRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  45. id := r.URL.Query().Get("id")
  46. if id == "" {
  47. return nil, ErrorBadRequest
  48. }
  49. return endpoint.CommentsListRequest{
  50. Id: id,
  51. }, nil
  52. }
  53. func encodeJSONResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  54. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  55. return json.NewEncoder(w).Encode(response)
  56. }
  57. func encodeError(_ context.Context, err error, w http.ResponseWriter) {
  58. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  59. switch err {
  60. default:
  61. w.WriteHeader(http.StatusInternalServerError)
  62. }
  63. json.NewEncoder(w).Encode(map[string]interface{}{
  64. "error": err.Error(),
  65. })
  66. }