Compare commits
3 Commits
Author | SHA1 | Date | |
---|---|---|---|
c0d9c34200 | |||
dc1e05bb18 | |||
1e4d56d059 |
@@ -3,6 +3,7 @@ package http
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -67,6 +68,8 @@ func (h *httpHandler) Options() server.HandlerOptions {
|
||||
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
path := r.URL.Path
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
h.errorHandler(ctx, h, w, r, fmt.Errorf("path must contains /"), http.StatusBadRequest)
|
||||
@@ -156,6 +159,10 @@ func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
//function := hldr.rcvr
|
||||
var returnValues []reflect.Value
|
||||
|
||||
if err = cf.ReadBody(r.Body, argv.Interface()); err != nil && err != io.EOF {
|
||||
h.errorHandler(ctx, h, w, r, err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
matches = rflutil.FlattenMap(matches)
|
||||
if err = rflutil.MergeMap(argv.Interface(), matches); err != nil {
|
||||
h.errorHandler(ctx, h, w, r, err, http.StatusBadRequest)
|
||||
|
22
http.go
22
http.go
@@ -375,7 +375,27 @@ func (h *httpServer) Start() error {
|
||||
}
|
||||
}
|
||||
|
||||
go http.Serve(ts, handler)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
if srvFunc != nil {
|
||||
go srvFunc(ts)
|
||||
} else {
|
||||
go http.Serve(ts, fn)
|
||||
}
|
||||
|
||||
go func() {
|
||||
t := new(time.Ticker)
|
||||
|
19
options.go
19
options.go
@@ -1,6 +1,11 @@
|
||||
package http
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/unistack-org/micro/v3/server"
|
||||
)
|
||||
|
||||
type rspCodeKey struct{}
|
||||
type rspCodeVal struct {
|
||||
@@ -22,3 +27,15 @@ func GetRspCode(ctx context.Context) int {
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
Reference in New Issue
Block a user