allow to have custom http.Server struct

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2021-02-07 19:03:38 +03:00
parent dc1e05bb18
commit c0d9c34200
2 changed files with 17 additions and 1 deletions

10
http.go
View File

@ -376,6 +376,8 @@ func (h *httpServer) Start() error {
} }
fn := handler fn := handler
var srvFunc func(net.Listener) error
if h.opts.Context != nil { if h.opts.Context != nil {
if mwf, ok := h.opts.Context.Value(middlewareKey{}).([]func(http.Handler) http.Handler); ok && len(mwf) > 0 { if mwf, ok := h.opts.Context.Value(middlewareKey{}).([]func(http.Handler) http.Handler); ok && len(mwf) > 0 {
// wrap the handler func // wrap the handler func
@ -383,9 +385,17 @@ func (h *httpServer) Start() error {
fn = mwf[i-1](fn) fn = mwf[i-1](fn)
} }
} }
if hs, ok := h.opts.Context.Value(serverKey{}).(*http.Server); ok && hs != nil {
hs.Handler = fn
srvFunc = hs.Serve
}
} }
if srvFunc != nil {
go srvFunc(ts)
} else {
go http.Serve(ts, fn) go http.Serve(ts, fn)
}
go func() { go func() {
t := new(time.Ticker) t := new(time.Ticker)

View File

@ -33,3 +33,9 @@ type middlewareKey struct{}
func Middleware(mw ...func(http.Handler) http.Handler) server.Option { func Middleware(mw ...func(http.Handler) http.Handler) server.Option {
return server.SetOption(middlewareKey{}, mw) return server.SetOption(middlewareKey{}, mw)
} }
type serverKey struct{}
func Server(hs *http.Server) server.Option {
return server.SetOption(serverKey{}, hs)
}