Compare commits

..

3 Commits

Author SHA1 Message Date
c0d9c34200 allow to have custom http.Server struct
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-07 19:03:38 +03:00
dc1e05bb18 allow to use http middlewares
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-07 13:27:28 +03:00
1e4d56d059 fix body parsing
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-06 18:53:25 +03:00
3 changed files with 46 additions and 2 deletions

View File

@@ -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
View File

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

View File

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