1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-11-24 08:02:32 +02:00

add option to set http handlers

This commit is contained in:
Asim Aslam 2018-11-18 16:32:53 +00:00
parent 98bb4a69c2
commit 1d8047a272
3 changed files with 37 additions and 0 deletions

View File

@ -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
View 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)
}
}

View File

@ -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,