afaf70da0ff47277d675c5ae62fe03bdffbf19b4.svn-base 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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/section14/register/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.RegisterEndpoints) 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("/health").Handler(kithttp.NewServer(
  28. endpoints.HealthCheckEndpoint,
  29. decodeHealthCheckRequest,
  30. encodeJSONResponse,
  31. options...,
  32. ))
  33. r.Methods("GET").Path("/discovery/name").Handler(kithttp.NewServer(
  34. endpoints.DiscoveryEndpoint,
  35. decodeDiscoveryRequest,
  36. encodeJSONResponse,
  37. options...,
  38. ))
  39. return r
  40. }
  41. func decodeDiscoveryRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  42. serviceName := r.URL.Query().Get("serviceName")
  43. if serviceName == ""{
  44. return nil, ErrorBadRequest
  45. }
  46. return endpoint.DiscoveryRequest{
  47. ServiceName:serviceName,
  48. }, nil
  49. }
  50. func decodeHealthCheckRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  51. return endpoint.HealthRequest{}, 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. }