1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package http
- import (
- "fmt"
- "net/http"
- "os"
- "os/signal"
- "syscall"
- "time"
- "github.com/go-kit/kit/endpoint"
- "github.com/go-kit/kit/log"
- httptransport "github.com/go-kit/kit/transport/http"
- )
- // TansportServerOptions default http transport options
- func TansportServerOptions(logger log.Logger) []httptransport.ServerOption {
- return []httptransport.ServerOption{
- httptransport.ServerErrorLogger(logger),
- httptransport.ServerErrorEncoder(EncodeError),
- httptransport.ServerBefore(PopulateRequestContext),
- }
- }
- // NewTansportServer new server hander
- func NewTansportServer(e endpoint.Endpoint, dec DecodeRequestFunc, enc EncodeResponseFunc, logger log.Logger) *httptransport.Server {
- options := TansportServerOptions(logger)
- return httptransport.NewServer(
- e,
- httptransport.DecodeRequestFunc(dec),
- httptransport.EncodeResponseFunc(enc),
- options...,
- )
- }
- // ListenAndServe new server and start
- func ListenAndServe(addr string, router http.Handler, readTimeout, writeTimeout time.Duration, maxHeaderBytes int, logger log.Logger) {
- server := &http.Server{
- Addr: addr,
- Handler: router,
- ReadTimeout: readTimeout,
- WriteTimeout: writeTimeout,
- MaxHeaderBytes: maxHeaderBytes,
- }
- // Interrupt handler.
- errc := make(chan error)
- go func() {
- c := make(chan os.Signal)
- signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
- errc <- fmt.Errorf("%s", <-c)
- }()
- // HTTP transport.
- go func() {
- logger.Log("Protocol", "HTTP", "addr", addr)
- errc <- server.ListenAndServe()
- logger.Log("Exit server", "Quit")
- }()
- // Run!
- logger.Log("Exit", <-errc)
- }
|