Merge pull request #328 from micro/http

add option to set http handlers
This commit is contained in:
Asim Aslam 2018-11-18 18:32:01 +00:00 committed by GitHub
commit 212c6c5ae9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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 package http
import ( import (
"github.com/micro/go-micro/transport" "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 { func NewTransport(opts ...transport.Option) transport.Transport {
return transport.NewTransport(opts...) 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 { func (h *httpTransportListener) Accept(fn func(Socket)) error {
// create handler mux // create handler mux
mux := http.NewServeMux() mux := http.NewServeMux()
// register our transport handler
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var buf *bufio.ReadWriter var buf *bufio.ReadWriter
var con net.Conn 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 // default http2 server
srv := &http.Server{ srv := &http.Server{
Handler: mux, Handler: mux,