Skip to content

Commit

Permalink
allow to have custom http.Server struct
Browse files Browse the repository at this point in the history
Signed-off-by: Vasiliy Tolstov <[email protected]>
  • Loading branch information
vtolstov committed Feb 7, 2021
1 parent dc1e05b commit c0d9c34
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
12 changes: 11 additions & 1 deletion http.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,16 +376,26 @@ func (h *httpServer) Start() error {
}

fn := handler
var srvFunc func(net.Listener) error

if h.opts.Context != nil {
if mwf, ok := h.opts.Context.Value(middlewareKey{}).([]func(http.Handler) http.Handler); ok && len(mwf) > 0 {
// wrap the handler func
for i := len(mwf); i > 0; i-- {
fn = mwf[i-1](fn)
}
}
if hs, ok := h.opts.Context.Value(serverKey{}).(*http.Server); ok && hs != nil {
hs.Handler = fn
srvFunc = hs.Serve
}
}

go http.Serve(ts, fn)
if srvFunc != nil {
go srvFunc(ts)
} else {
go http.Serve(ts, fn)
}

go func() {
t := new(time.Ticker)
Expand Down
6 changes: 6 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,9 @@ type middlewareKey struct{}
func Middleware(mw ...func(http.Handler) http.Handler) server.Option {
return server.SetOption(middlewareKey{}, mw)
}

type serverKey struct{}

func Server(hs *http.Server) server.Option {
return server.SetOption(serverKey{}, hs)
}

0 comments on commit c0d9c34

Please sign in to comment.