ec8fcb05fb6f8e1c129178ae70f676fbff5419d3.svn-base 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/go-kit/kit/log"
  7. "github.com/go-kit/kit/tracing/zipkin"
  8. kithttp "github.com/go-kit/kit/transport/http"
  9. "github.com/gorilla/mux"
  10. "github.com/longjoy/micro-go-course/section35/zipkin-kit/string-service/endpoint"
  11. gozipkin "github.com/openzipkin/zipkin-go"
  12. "github.com/prometheus/client_golang/prometheus/promhttp"
  13. "net/http"
  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.StringEndpoints, zipkinTracer *gozipkin.Tracer, logger log.Logger) http.Handler {
  20. r := mux.NewRouter()
  21. zipkinServer := zipkin.HTTPServerTrace(zipkinTracer, zipkin.Name("http-transport"))
  22. options := []kithttp.ServerOption{
  23. kithttp.ServerErrorLogger(logger),
  24. kithttp.ServerErrorEncoder(kithttp.DefaultErrorEncoder),
  25. zipkinServer,
  26. }
  27. r.Methods("POST").Path("/op/{type}/{a}/{b}").Handler(kithttp.NewServer(
  28. endpoints.StringEndpoint,
  29. decodeStringRequest,
  30. encodeStringResponse,
  31. options...,
  32. ))
  33. r.Path("/metrics").Handler(promhttp.Handler())
  34. // create health check handler
  35. r.Methods("GET").Path("/health").Handler(kithttp.NewServer(
  36. endpoints.HealthCheckEndpoint,
  37. decodeHealthCheckRequest,
  38. encodeStringResponse,
  39. options...,
  40. ))
  41. return r
  42. }
  43. // decodeStringRequest decode request params to struct
  44. func decodeStringRequest(_ context.Context, r *http.Request) (interface{}, error) {
  45. vars := mux.Vars(r)
  46. requestType, ok := vars["type"]
  47. if !ok {
  48. return nil, ErrorBadRequest
  49. }
  50. pa, ok := vars["a"]
  51. if !ok {
  52. return nil, ErrorBadRequest
  53. }
  54. pb, ok := vars["b"]
  55. if !ok {
  56. return nil, ErrorBadRequest
  57. }
  58. return endpoint.StringRequest{
  59. RequestType: requestType,
  60. A: pa,
  61. B: pb,
  62. }, nil
  63. }
  64. // encodeStringResponse encode response to return
  65. func encodeStringResponse(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. // decodeHealthCheckRequest decode request
  70. func decodeHealthCheckRequest(ctx context.Context, r *http.Request) (interface{}, error) {
  71. return endpoint.HealthRequest{}, nil
  72. }