http.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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/section24/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. return r
  34. }
  35. func decodeCommentsListRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  36. id := r.URL.Query().Get("id")
  37. if id == "" {
  38. return nil, ErrorBadRequest
  39. }
  40. return endpoint.CommentsListRequest{
  41. Id: id,
  42. }, nil
  43. }
  44. func encodeJSONResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  45. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  46. return json.NewEncoder(w).Encode(response)
  47. }
  48. func encodeError(_ context.Context, err error, w http.ResponseWriter) {
  49. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  50. switch err {
  51. default:
  52. w.WriteHeader(http.StatusInternalServerError)
  53. }
  54. json.NewEncoder(w).Encode(map[string]interface{}{
  55. "error": err.Error(),
  56. })
  57. }