server.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package http
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "os/signal"
  7. "syscall"
  8. "time"
  9. "github.com/go-kit/kit/endpoint"
  10. "github.com/go-kit/kit/log"
  11. httptransport "github.com/go-kit/kit/transport/http"
  12. )
  13. // TansportServerOptions default http transport options
  14. func TansportServerOptions(logger log.Logger) []httptransport.ServerOption {
  15. return []httptransport.ServerOption{
  16. httptransport.ServerErrorLogger(logger),
  17. httptransport.ServerErrorEncoder(EncodeError),
  18. httptransport.ServerBefore(PopulateRequestContext),
  19. }
  20. }
  21. // NewTansportServer new server hander
  22. func NewTansportServer(e endpoint.Endpoint, dec DecodeRequestFunc, enc EncodeResponseFunc, logger log.Logger) *httptransport.Server {
  23. options := TansportServerOptions(logger)
  24. return httptransport.NewServer(
  25. e,
  26. httptransport.DecodeRequestFunc(dec),
  27. httptransport.EncodeResponseFunc(enc),
  28. options...,
  29. )
  30. }
  31. // ListenAndServe new server and start
  32. func ListenAndServe(addr string, router http.Handler, readTimeout, writeTimeout time.Duration, maxHeaderBytes int, logger log.Logger) {
  33. server := &http.Server{
  34. Addr: addr,
  35. Handler: router,
  36. ReadTimeout: readTimeout,
  37. WriteTimeout: writeTimeout,
  38. MaxHeaderBytes: maxHeaderBytes,
  39. }
  40. // Interrupt handler.
  41. errc := make(chan error)
  42. go func() {
  43. c := make(chan os.Signal)
  44. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  45. errc <- fmt.Errorf("%s", <-c)
  46. }()
  47. // HTTP transport.
  48. go func() {
  49. logger.Log("Protocol", "HTTP", "addr", addr)
  50. errc <- server.ListenAndServe()
  51. logger.Log("Exit server", "Quit")
  52. }()
  53. // Run!
  54. logger.Log("Exit", <-errc)
  55. }