http.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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/section10/user/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.UserEndpoints) 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("POST").Path("/register").Handler(kithttp.NewServer(
  28. endpoints.RegisterEndpoint,
  29. decodeRegisterRequest,
  30. encodeJSONResponse,
  31. options...,
  32. ))
  33. r.Methods("POST").Path("/login").Handler(kithttp.NewServer(
  34. endpoints.LoginEndpoint,
  35. decodeLoginRequest,
  36. encodeJSONResponse,
  37. options...,
  38. ))
  39. return r
  40. }
  41. func decodeRegisterRequest(_ context.Context, r *http.Request) (interface{}, error) {
  42. username := r.FormValue("username")
  43. password := r.FormValue("password")
  44. email := r.FormValue("email")
  45. if username == "" || password == "" || email == ""{
  46. return nil, ErrorBadRequest
  47. }
  48. return &endpoint.RegisterRequest{
  49. Username:username,
  50. Password:password,
  51. Email:email,
  52. },nil
  53. }
  54. func decodeLoginRequest(_ context.Context, r *http.Request) (interface{}, error) {
  55. email := r.FormValue("email")
  56. password := r.FormValue("password")
  57. if email == "" || password == "" {
  58. return nil, ErrorBadRequest
  59. }
  60. return &endpoint.LoginRequest{
  61. Email:email,
  62. Password:password,
  63. },nil
  64. }
  65. func encodeJSONResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  66. w.Header().Set("Content-Type", "application/json;charset=utf-8")
  67. return json.NewEncoder(w).Encode(response)
  68. }
  69. func encodeError(_ context.Context, err error, w http.ResponseWriter) {
  70. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  71. switch err {
  72. default:
  73. w.WriteHeader(http.StatusInternalServerError)
  74. }
  75. json.NewEncoder(w).Encode(map[string]interface{}{
  76. "error": err.Error(),
  77. })
  78. }