add option to set http handlers
This commit is contained in:
parent
98bb4a69c2
commit
1d8047a272
@ -1,9 +1,11 @@
|
||||
// Package http returns a http2 transport using net/http
|
||||
package http
|
||||
|
||||
import (
|
||||
"github.com/micro/go-micro/transport"
|
||||
)
|
||||
|
||||
// NewTransport returns a new http transport using net/http and supporting http2
|
||||
func NewTransport(opts ...transport.Option) transport.Transport {
|
||||
return transport.NewTransport(opts...)
|
||||
}
|
||||
|
23
transport/http/options.go
Normal file
23
transport/http/options.go
Normal file
@ -0,0 +1,23 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/micro/go-micro/transport"
|
||||
)
|
||||
|
||||
// Handle registers the handler for the given pattern.
|
||||
func Handle(pattern string, handler http.Handler) transport.Option {
|
||||
return func(o *transport.Options) {
|
||||
if o.Context == nil {
|
||||
o.Context = context.Background()
|
||||
}
|
||||
handlers, ok := o.Context.Value("http_handlers").(map[string]http.Handler)
|
||||
if !ok {
|
||||
handlers = make(map[string]http.Handler)
|
||||
}
|
||||
handlers[pattern] = handler
|
||||
o.Context = context.WithValue(o.Context, "http_handlers", handlers)
|
||||
}
|
||||
}
|
@ -357,6 +357,8 @@ func (h *httpTransportListener) Close() error {
|
||||
func (h *httpTransportListener) Accept(fn func(Socket)) error {
|
||||
// create handler mux
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// register our transport handler
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
var buf *bufio.ReadWriter
|
||||
var con net.Conn
|
||||
@ -403,6 +405,16 @@ func (h *httpTransportListener) Accept(fn func(Socket)) error {
|
||||
})
|
||||
})
|
||||
|
||||
// get optional handlers
|
||||
if h.ht.opts.Context != nil {
|
||||
handlers, ok := h.ht.opts.Context.Value("http_handlers").(map[string]http.Handler)
|
||||
if ok {
|
||||
for pattern, handler := range handlers {
|
||||
mux.Handle(pattern, handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// default http2 server
|
||||
srv := &http.Server{
|
||||
Handler: mux,
|
||||
|
Loading…
Reference in New Issue
Block a user