Compare commits
31 Commits
Author | SHA1 | Date | |
---|---|---|---|
12e26d0018 | |||
aab779b406 | |||
3514bb9626 | |||
c7dc998670 | |||
954101f887 | |||
4c3d26c39b | |||
a483e08ffa | |||
28eeca30c0 | |||
2e8462a0f1 | |||
1432587369 | |||
ea8c9dd22e | |||
49608197d0 | |||
41d7d145ce | |||
1d5142d619 | |||
41f7bdf182 | |||
ed907c7076 | |||
5c2cba3ecc | |||
966bc31eb2 | |||
259e1d275e | |||
fdbcff2ba0 | |||
3e814bf229 | |||
13cdeb9397 | |||
0e19afef86 | |||
7e850f75e0 | |||
4c3d3058f6 | |||
bcd27b833a | |||
090b5e3c07 | |||
95109c9dc2 | |||
69dcf71d3f | |||
0a0a986a70 | |||
76fe748e4a |
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
# Binaries for programs and plugins
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
bin
|
||||||
|
|
||||||
|
# Test binary, built with `go test -c`
|
||||||
|
*.test
|
||||||
|
|
||||||
|
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||||
|
*.out
|
||||||
|
|
||||||
|
# Dependency directories (remove the comment below to include it)
|
||||||
|
# vendor/
|
||||||
|
|
||||||
|
# Go workspace file
|
||||||
|
go.work
|
||||||
|
|
||||||
|
# General
|
||||||
|
.DS_Store
|
||||||
|
.idea
|
||||||
|
.vscode
|
21
go.mod
21
go.mod
@ -3,14 +3,23 @@ module go.unistack.org/micro-server-http/v4
|
|||||||
go 1.19
|
go 1.19
|
||||||
|
|
||||||
require (
|
require (
|
||||||
go.unistack.org/micro-proto/v4 v4.0.0
|
go.unistack.org/micro-codec-yaml/v4 v4.0.0
|
||||||
go.unistack.org/micro/v4 v4.0.1
|
go.unistack.org/micro-proto/v4 v4.0.1
|
||||||
golang.org/x/net v0.7.0
|
go.unistack.org/micro/v4 v4.0.17
|
||||||
|
go.unistack.org/protoc-gen-go-micro/v4 v4.0.13
|
||||||
|
golang.org/x/net v0.22.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/golang/protobuf v1.5.2 // indirect
|
github.com/fatih/structtag v1.2.0 // indirect
|
||||||
github.com/google/gnostic v0.6.9 // indirect
|
github.com/golang/protobuf v1.5.4 // indirect
|
||||||
google.golang.org/protobuf v1.28.1 // indirect
|
github.com/google/gnostic v0.7.0 // indirect
|
||||||
|
github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 // indirect
|
||||||
|
golang.org/x/mod v0.16.0 // indirect
|
||||||
|
golang.org/x/sys v0.18.0 // indirect
|
||||||
|
golang.org/x/tools v0.19.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.33.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
sigs.k8s.io/yaml v1.4.0 // indirect
|
||||||
)
|
)
|
||||||
|
90
handler.go
90
handler.go
@ -19,10 +19,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
DefaultErrorHandler = func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int) {
|
DefaultErrorHandler = func(ctx context.Context, s interface{}, w http.ResponseWriter, r *http.Request, err error, status int) {
|
||||||
w.WriteHeader(status)
|
w.WriteHeader(status)
|
||||||
if _, cerr := w.Write([]byte(err.Error())); cerr != nil {
|
if _, cerr := w.Write([]byte(err.Error())); cerr != nil {
|
||||||
logger.DefaultLogger.Errorf(ctx, "write failed: %v", cerr)
|
logger.DefaultLogger.Error(ctx, fmt.Sprintf("write failed: %v", cerr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DefaultContentType = "application/json"
|
DefaultContentType = "application/json"
|
||||||
@ -35,7 +35,7 @@ type patHandler struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type httpHandler struct {
|
type httpHandler struct {
|
||||||
opts server.HandlerOptions
|
opts server.HandleOptions
|
||||||
hd interface{}
|
hd interface{}
|
||||||
handlers *rhttp.Trie
|
handlers *rhttp.Trie
|
||||||
name string
|
name string
|
||||||
@ -56,7 +56,7 @@ func (h *httpHandler) Endpoints() []*register.Endpoint {
|
|||||||
return h.eps
|
return h.eps
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *httpHandler) Options() server.HandlerOptions {
|
func (h *httpHandler) Options() server.HandleOptions {
|
||||||
return h.opts
|
return h.opts
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,16 +109,22 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
|||||||
md = metadata.New(len(r.Header) + 8)
|
md = metadata.New(len(r.Header) + 8)
|
||||||
}
|
}
|
||||||
for k, v := range r.Header {
|
for k, v := range r.Header {
|
||||||
md[k] = strings.Join(v, ", ")
|
md[k] = v[0]
|
||||||
}
|
}
|
||||||
md["RemoteAddr"] = r.RemoteAddr
|
md["RemoteAddr"] = r.RemoteAddr
|
||||||
md["Method"] = r.Method
|
md["Method"] = r.Method
|
||||||
md["URL"] = r.URL.String()
|
md["URL"] = r.URL.String()
|
||||||
md["Proto"] = r.Proto
|
md["Proto"] = r.Proto
|
||||||
md["ContentLength"] = fmt.Sprintf("%d", r.ContentLength)
|
md["Content-Length"] = fmt.Sprintf("%d", r.ContentLength)
|
||||||
md["TransferEncoding"] = strings.Join(r.TransferEncoding, ",")
|
md["Transfer-Encoding"] = r.TransferEncoding[0]
|
||||||
md["Host"] = r.Host
|
md["Host"] = r.Host
|
||||||
md["RequestURI"] = r.RequestURI
|
md["RequestURI"] = r.RequestURI
|
||||||
|
if r.TLS != nil {
|
||||||
|
md["TLS"] = "true"
|
||||||
|
md["TLS-ALPN"] = r.TLS.NegotiatedProtocol
|
||||||
|
md["TLS-ServerName"] = r.TLS.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
ctx = metadata.NewIncomingContext(ctx, md)
|
ctx = metadata.NewIncomingContext(ctx, md)
|
||||||
|
|
||||||
path := r.URL.Path
|
path := r.URL.Path
|
||||||
@ -257,18 +263,17 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
|||||||
}
|
}
|
||||||
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
|
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
|
||||||
for k, v := range nmd {
|
for k, v := range nmd {
|
||||||
md.Set(k, v)
|
md[k] = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
metadata.SetOutgoingContext(ctx, md)
|
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// wrap the handler func
|
// wrap the handler func
|
||||||
for i := len(handler.sopts.HdlrWrappers); i > 0; i-- {
|
// for i := len(handler.sopts.Hooks); i > 0; i-- {
|
||||||
fn = handler.sopts.HdlrWrappers[i-1](fn)
|
// fn = handler.sopts.Hooks[i-1](fn)
|
||||||
}
|
// }
|
||||||
|
|
||||||
if ct == "application/x-www-form-urlencoded" {
|
if ct == "application/x-www-form-urlencoded" {
|
||||||
cf, err = h.newCodec(DefaultContentType)
|
cf, err = h.newCodec(DefaultContentType)
|
||||||
@ -285,14 +290,12 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
|||||||
w.Header().Set(metadata.HeaderContentType, ct)
|
w.Header().Set(metadata.HeaderContentType, ct)
|
||||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||||
for k, v := range md {
|
for k, v := range md {
|
||||||
w.Header().Set(k, v)
|
w.Header()[k] = []string{v}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if md := getRspHeader(ctx); md != nil {
|
if md := getRspHeader(ctx); md != nil {
|
||||||
for k, v := range md {
|
for k, v := range md {
|
||||||
for _, vv := range v {
|
w.Header()[k] = v
|
||||||
w.Header().Add(k, vv)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
|
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
|
||||||
@ -318,7 +321,7 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
|
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
|
||||||
handler.sopts.Logger.Errorf(handler.sopts.Context, "handler err: %v", err)
|
handler.sopts.Logger.Error(handler.sopts.Context, fmt.Sprintf("handler err: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -328,18 +331,12 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
|||||||
w.WriteHeader(scode)
|
w.WriteHeader(scode)
|
||||||
|
|
||||||
if _, cerr := w.Write(buf); cerr != nil {
|
if _, cerr := w.Write(buf); cerr != nil {
|
||||||
handler.sopts.Logger.Errorf(ctx, "write failed: %v", cerr)
|
handler.sopts.Logger.Error(ctx, fmt.Sprintf("write failed: %v", cerr))
|
||||||
}
|
}
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
// check for http.HandlerFunc handlers
|
|
||||||
if ph, _, err := h.pathHandlers.Search(r.Method, r.URL.Path); err == nil {
|
|
||||||
ph.(http.HandlerFunc)(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ct := DefaultContentType
|
ct := DefaultContentType
|
||||||
if htype := r.Header.Get(metadata.HeaderContentType); htype != "" {
|
if htype := r.Header.Get(metadata.HeaderContentType); htype != "" {
|
||||||
ct = htype
|
ct = htype
|
||||||
@ -352,22 +349,25 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
md = metadata.New(len(r.Header) + 8)
|
md = metadata.New(len(r.Header) + 8)
|
||||||
}
|
}
|
||||||
for k, v := range r.Header {
|
for k, v := range r.Header {
|
||||||
md[k] = strings.Join(v, ", ")
|
md[k] = v[0]
|
||||||
}
|
}
|
||||||
md["RemoteAddr"] = r.RemoteAddr
|
md["RemoteAddr"] = r.RemoteAddr
|
||||||
|
if r.TLS != nil {
|
||||||
|
md["Scheme"] = "https"
|
||||||
|
} else {
|
||||||
|
md["Scheme"] = "http"
|
||||||
|
}
|
||||||
md["Method"] = r.Method
|
md["Method"] = r.Method
|
||||||
md["URL"] = r.URL.String()
|
md["URL"] = r.URL.String()
|
||||||
md["Proto"] = r.Proto
|
md["Proto"] = r.Proto
|
||||||
md["ContentLength"] = fmt.Sprintf("%d", r.ContentLength)
|
md["Content-Length"] = fmt.Sprintf("%d", r.ContentLength)
|
||||||
md["TransferEncoding"] = strings.Join(r.TransferEncoding, ",")
|
if len(r.TransferEncoding) > 0 {
|
||||||
|
md["Transfer-Encoding"] = r.TransferEncoding[0]
|
||||||
|
}
|
||||||
md["Host"] = r.Host
|
md["Host"] = r.Host
|
||||||
md["RequestURI"] = r.RequestURI
|
md["RequestURI"] = r.RequestURI
|
||||||
ctx = metadata.NewIncomingContext(ctx, md)
|
ctx = metadata.NewIncomingContext(ctx, md)
|
||||||
|
|
||||||
if r.Body != nil {
|
|
||||||
defer r.Body.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
path := r.URL.Path
|
path := r.URL.Path
|
||||||
if !strings.HasPrefix(path, "/") {
|
if !strings.HasPrefix(path, "/") {
|
||||||
h.errorHandler(ctx, nil, w, r, fmt.Errorf("path must starts with /"), http.StatusBadRequest)
|
h.errorHandler(ctx, nil, w, r, fmt.Errorf("path must starts with /"), http.StatusBadRequest)
|
||||||
@ -419,11 +419,16 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !match && h.hd != nil {
|
if !match && h.hd != nil {
|
||||||
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
|
if hdlr, ok := h.hd.(http.Handler); ok {
|
||||||
hdlr.ServeHTTP(w, r)
|
hdlr.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else if !match {
|
} else if !match {
|
||||||
|
// check for http.HandlerFunc handlers
|
||||||
|
if ph, _, err := h.pathHandlers.Search(r.Method, r.URL.Path); err == nil {
|
||||||
|
ph.(http.HandlerFunc)(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
h.errorHandler(ctx, nil, w, r, fmt.Errorf("not matching route found"), http.StatusNotFound)
|
h.errorHandler(ctx, nil, w, r, fmt.Errorf("not matching route found"), http.StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -440,6 +445,10 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if r.Body != nil {
|
||||||
|
defer r.Body.Close()
|
||||||
|
}
|
||||||
|
|
||||||
cf, err := h.newCodec(ct)
|
cf, err := h.newCodec(ct)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.errorHandler(ctx, nil, w, r, err, http.StatusBadRequest)
|
h.errorHandler(ctx, nil, w, r, err, http.StatusBadRequest)
|
||||||
@ -481,11 +490,13 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(matches) > 0 {
|
||||||
matches = rflutil.FlattenMap(matches)
|
matches = rflutil.FlattenMap(matches)
|
||||||
if err = rflutil.Merge(argv.Interface(), matches, rflutil.SliceAppend(true), rflutil.Tags([]string{"protobuf", "json"})); err != nil {
|
if err = rflutil.Merge(argv.Interface(), matches, rflutil.SliceAppend(true), rflutil.Tags([]string{"protobuf", "json"})); err != nil {
|
||||||
h.errorHandler(ctx, handler, w, r, err, http.StatusBadRequest)
|
h.errorHandler(ctx, handler, w, r, err, http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
hr := &rpcRequest{
|
hr := &rpcRequest{
|
||||||
codec: cf,
|
codec: cf,
|
||||||
@ -512,18 +523,17 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
|
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
|
||||||
for k, v := range nmd {
|
for k, v := range nmd {
|
||||||
md.Set(k, v)
|
md[k] = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
metadata.SetOutgoingContext(ctx, md)
|
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// wrap the handler func
|
// wrap the handler func
|
||||||
for i := len(handler.sopts.HdlrWrappers); i > 0; i-- {
|
// for i := len(handler.sopts.HdlrWrappers); i > 0; i-- {
|
||||||
fn = handler.sopts.HdlrWrappers[i-1](fn)
|
// fn = handler.sopts.HdlrWrappers[i-1](fn)
|
||||||
}
|
// }
|
||||||
|
|
||||||
if ct == "application/x-www-form-urlencoded" {
|
if ct == "application/x-www-form-urlencoded" {
|
||||||
cf, err = h.newCodec(DefaultContentType)
|
cf, err = h.newCodec(DefaultContentType)
|
||||||
@ -540,7 +550,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set(metadata.HeaderContentType, ct)
|
w.Header().Set(metadata.HeaderContentType, ct)
|
||||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||||
for k, v := range md {
|
for k, v := range md {
|
||||||
w.Header().Set(k, v)
|
w.Header()[k] = []string{v}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if md := getRspHeader(ctx); md != nil {
|
if md := getRspHeader(ctx); md != nil {
|
||||||
@ -573,7 +583,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
|
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
|
||||||
handler.sopts.Logger.Errorf(handler.sopts.Context, "handler err: %v", err)
|
handler.sopts.Logger.Error(handler.sopts.Context, fmt.Sprintf("handler err: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -583,6 +593,6 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.WriteHeader(scode)
|
w.WriteHeader(scode)
|
||||||
|
|
||||||
if _, cerr := w.Write(buf); cerr != nil {
|
if _, cerr := w.Write(buf); cerr != nil {
|
||||||
handler.sopts.Logger.Errorf(ctx, "write failed: %v", cerr)
|
handler.sopts.Logger.Error(ctx, fmt.Sprintf("write failed: %v", cerr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
||||||
// versions:
|
// versions:
|
||||||
// - protoc-gen-go-micro v4.0.0
|
// - protoc-gen-go-micro v4.0.2
|
||||||
// - protoc v3.21.12
|
// - protoc v4.23.4
|
||||||
// source: health/health.proto
|
// source: health/health.proto
|
||||||
|
|
||||||
package health
|
package health
|
||||||
@ -9,37 +9,11 @@ package health
|
|||||||
import (
|
import (
|
||||||
context "context"
|
context "context"
|
||||||
codec "go.unistack.org/micro-proto/v4/codec"
|
codec "go.unistack.org/micro-proto/v4/codec"
|
||||||
v4 "go.unistack.org/micro-server-http/v4"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
HealthServiceName = "HealthService"
|
HealthServiceName = "HealthService"
|
||||||
)
|
)
|
||||||
var (
|
|
||||||
HealthServiceServerEndpoints = []v4.EndpointMetadata{
|
|
||||||
{
|
|
||||||
Name: "HealthService.Live",
|
|
||||||
Path: "/live",
|
|
||||||
Method: "GET",
|
|
||||||
Body: "",
|
|
||||||
Stream: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "HealthService.Ready",
|
|
||||||
Path: "/ready",
|
|
||||||
Method: "GET",
|
|
||||||
Body: "",
|
|
||||||
Stream: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "HealthService.Version",
|
|
||||||
Path: "/version",
|
|
||||||
Method: "GET",
|
|
||||||
Body: "",
|
|
||||||
Stream: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
type HealthServiceServer interface {
|
type HealthServiceServer interface {
|
||||||
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
||||||
// protoc-gen-go-micro version: v4.0.0
|
// protoc-gen-go-micro version: v4.0.2
|
||||||
// source: health/health.proto
|
// source: health/health.proto
|
||||||
|
|
||||||
package health
|
package health
|
||||||
@ -8,9 +8,36 @@ import (
|
|||||||
context "context"
|
context "context"
|
||||||
codec "go.unistack.org/micro-proto/v4/codec"
|
codec "go.unistack.org/micro-proto/v4/codec"
|
||||||
v4 "go.unistack.org/micro-server-http/v4"
|
v4 "go.unistack.org/micro-server-http/v4"
|
||||||
|
options "go.unistack.org/micro/v4/options"
|
||||||
server "go.unistack.org/micro/v4/server"
|
server "go.unistack.org/micro/v4/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
HealthServiceServerEndpoints = []v4.EndpointMetadata{
|
||||||
|
{
|
||||||
|
Name: "HealthService.Live",
|
||||||
|
Path: "/live",
|
||||||
|
Method: "GET",
|
||||||
|
Body: "",
|
||||||
|
Stream: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "HealthService.Ready",
|
||||||
|
Path: "/ready",
|
||||||
|
Method: "GET",
|
||||||
|
Body: "",
|
||||||
|
Stream: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "HealthService.Version",
|
||||||
|
Path: "/version",
|
||||||
|
Method: "GET",
|
||||||
|
Body: "",
|
||||||
|
Stream: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
type healthServiceServer struct {
|
type healthServiceServer struct {
|
||||||
HealthServiceServer
|
HealthServiceServer
|
||||||
}
|
}
|
||||||
@ -27,7 +54,7 @@ func (h *healthServiceServer) Version(ctx context.Context, req *codec.Frame, rsp
|
|||||||
return h.HealthServiceServer.Version(ctx, req, rsp)
|
return h.HealthServiceServer.Version(ctx, req, rsp)
|
||||||
}
|
}
|
||||||
|
|
||||||
func RegisterHealthServiceServer(s server.Server, sh HealthServiceServer, opts ...server.HandlerOption) error {
|
func RegisterHealthServiceServer(s server.Server, sh HealthServiceServer, opts ...options.Option) error {
|
||||||
type healthService interface {
|
type healthService interface {
|
||||||
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
||||||
Ready(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
Ready(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
||||||
@ -37,7 +64,7 @@ func RegisterHealthServiceServer(s server.Server, sh HealthServiceServer, opts .
|
|||||||
healthService
|
healthService
|
||||||
}
|
}
|
||||||
h := &healthServiceServer{sh}
|
h := &healthServiceServer{sh}
|
||||||
var nopts []server.HandlerOption
|
var nopts []options.Option
|
||||||
nopts = append(nopts, v4.HandlerEndpoints(HealthServiceServerEndpoints))
|
nopts = append(nopts, v4.HandlerEndpoints(HealthServiceServerEndpoints))
|
||||||
return s.Handle(s.NewHandler(&HealthService{h}, append(nopts, opts...)...))
|
return s.Handle(&HealthService{h}, append(nopts, opts...)...)
|
||||||
}
|
}
|
||||||
|
@ -2,13 +2,36 @@ package meter // import "go.unistack.org/micro-server-http/v4/handler/meter"
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
"context"
|
"context"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
codecpb "go.unistack.org/micro-proto/v4/codec"
|
codecpb "go.unistack.org/micro-proto/v4/codec"
|
||||||
"go.unistack.org/micro/v4/errors"
|
"go.unistack.org/micro/v4/logger"
|
||||||
|
"go.unistack.org/micro/v4/metadata"
|
||||||
"go.unistack.org/micro/v4/meter"
|
"go.unistack.org/micro/v4/meter"
|
||||||
|
"go.unistack.org/micro/v4/options"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
contentEncodingHeader = "Content-Encoding"
|
||||||
|
acceptEncodingHeader = "Accept-Encoding"
|
||||||
|
)
|
||||||
|
|
||||||
|
var gzipPool = sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return gzip.NewWriter(nil)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var bufPool = sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return bytes.NewBuffer(nil)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
// guard to fail early
|
// guard to fail early
|
||||||
var _ MeterServiceServer = (*Handler)(nil)
|
var _ MeterServiceServer = (*Handler)(nil)
|
||||||
|
|
||||||
@ -21,7 +44,8 @@ type Option func(*Options)
|
|||||||
type Options struct {
|
type Options struct {
|
||||||
Meter meter.Meter
|
Meter meter.Meter
|
||||||
Name string
|
Name string
|
||||||
MeterOptions []meter.Option
|
MeterOptions []options.Option
|
||||||
|
DisableCompress bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func Meter(m meter.Meter) Option {
|
func Meter(m meter.Meter) Option {
|
||||||
@ -36,14 +60,20 @@ func Name(name string) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func MeterOptions(opts ...meter.Option) Option {
|
func DisableCompress(g bool) Option {
|
||||||
|
return func(o *Options) {
|
||||||
|
o.DisableCompress = g
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func MeterOptions(opts ...options.Option) Option {
|
||||||
return func(o *Options) {
|
return func(o *Options) {
|
||||||
o.MeterOptions = append(o.MeterOptions, opts...)
|
o.MeterOptions = append(o.MeterOptions, opts...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewOptions(opts ...Option) Options {
|
func NewOptions(opts ...Option) Options {
|
||||||
options := Options{Meter: meter.DefaultMeter}
|
options := Options{Meter: meter.DefaultMeter, DisableCompress: false}
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&options)
|
o(&options)
|
||||||
}
|
}
|
||||||
@ -56,12 +86,48 @@ func NewHandler(opts ...Option) *Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.Frame) error {
|
func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.Frame) error {
|
||||||
buf := bytes.NewBuffer(nil)
|
log, ok := logger.FromContext(ctx)
|
||||||
if err := h.opts.Meter.Write(buf, h.opts.MeterOptions...); err != nil {
|
if !ok {
|
||||||
return errors.InternalServerError(h.opts.Name, "%v", err)
|
log = logger.DefaultLogger
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := bufPool.Get().(*bytes.Buffer)
|
||||||
|
defer bufPool.Put(buf)
|
||||||
|
buf.Reset()
|
||||||
|
|
||||||
|
w := io.Writer(buf)
|
||||||
|
|
||||||
|
if md, ok := metadata.FromIncomingContext(ctx); gzipAccepted(md) && ok && !h.opts.DisableCompress {
|
||||||
|
omd, _ := metadata.FromOutgoingContext(ctx)
|
||||||
|
omd.Set(contentEncodingHeader, "gzip")
|
||||||
|
gz := gzipPool.Get().(*gzip.Writer)
|
||||||
|
defer gzipPool.Put(gz)
|
||||||
|
|
||||||
|
gz.Reset(w)
|
||||||
|
defer gz.Close()
|
||||||
|
|
||||||
|
w = gz
|
||||||
|
gz.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.opts.Meter.Write(w, h.opts.MeterOptions...); err != nil {
|
||||||
|
log.Error(ctx, "http/meter: write failed", err)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
rsp.Data = buf.Bytes()
|
rsp.Data = buf.Bytes()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// gzipAccepted returns whether the client will accept gzip-encoded content.
|
||||||
|
func gzipAccepted(md metadata.Metadata) bool {
|
||||||
|
a, ok := md.Get(acceptEncodingHeader)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.Contains(a, "gzip") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
||||||
// versions:
|
// versions:
|
||||||
// - protoc-gen-go-micro v4.0.0
|
// - protoc-gen-go-micro v4.0.2
|
||||||
// - protoc v3.21.12
|
// - protoc v4.23.4
|
||||||
// source: meter/meter.proto
|
// source: meter/meter.proto
|
||||||
|
|
||||||
package meter
|
package meter
|
||||||
@ -9,23 +9,11 @@ package meter
|
|||||||
import (
|
import (
|
||||||
context "context"
|
context "context"
|
||||||
codec "go.unistack.org/micro-proto/v4/codec"
|
codec "go.unistack.org/micro-proto/v4/codec"
|
||||||
v4 "go.unistack.org/micro-server-http/v4"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
MeterServiceName = "MeterService"
|
MeterServiceName = "MeterService"
|
||||||
)
|
)
|
||||||
var (
|
|
||||||
MeterServiceServerEndpoints = []v4.EndpointMetadata{
|
|
||||||
{
|
|
||||||
Name: "MeterService.Metrics",
|
|
||||||
Path: "/metrics",
|
|
||||||
Method: "GET",
|
|
||||||
Body: "",
|
|
||||||
Stream: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
type MeterServiceServer interface {
|
type MeterServiceServer interface {
|
||||||
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
|
||||||
// protoc-gen-go-micro version: v4.0.0
|
// protoc-gen-go-micro version: v4.0.2
|
||||||
// source: meter/meter.proto
|
// source: meter/meter.proto
|
||||||
|
|
||||||
package meter
|
package meter
|
||||||
@ -8,9 +8,22 @@ import (
|
|||||||
context "context"
|
context "context"
|
||||||
codec "go.unistack.org/micro-proto/v4/codec"
|
codec "go.unistack.org/micro-proto/v4/codec"
|
||||||
v4 "go.unistack.org/micro-server-http/v4"
|
v4 "go.unistack.org/micro-server-http/v4"
|
||||||
|
options "go.unistack.org/micro/v4/options"
|
||||||
server "go.unistack.org/micro/v4/server"
|
server "go.unistack.org/micro/v4/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
MeterServiceServerEndpoints = []v4.EndpointMetadata{
|
||||||
|
{
|
||||||
|
Name: "MeterService.Metrics",
|
||||||
|
Path: "/metrics",
|
||||||
|
Method: "GET",
|
||||||
|
Body: "",
|
||||||
|
Stream: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
type meterServiceServer struct {
|
type meterServiceServer struct {
|
||||||
MeterServiceServer
|
MeterServiceServer
|
||||||
}
|
}
|
||||||
@ -19,7 +32,7 @@ func (h *meterServiceServer) Metrics(ctx context.Context, req *codec.Frame, rsp
|
|||||||
return h.MeterServiceServer.Metrics(ctx, req, rsp)
|
return h.MeterServiceServer.Metrics(ctx, req, rsp)
|
||||||
}
|
}
|
||||||
|
|
||||||
func RegisterMeterServiceServer(s server.Server, sh MeterServiceServer, opts ...server.HandlerOption) error {
|
func RegisterMeterServiceServer(s server.Server, sh MeterServiceServer, opts ...options.Option) error {
|
||||||
type meterService interface {
|
type meterService interface {
|
||||||
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
|
||||||
}
|
}
|
||||||
@ -27,7 +40,7 @@ func RegisterMeterServiceServer(s server.Server, sh MeterServiceServer, opts ...
|
|||||||
meterService
|
meterService
|
||||||
}
|
}
|
||||||
h := &meterServiceServer{sh}
|
h := &meterServiceServer{sh}
|
||||||
var nopts []server.HandlerOption
|
var nopts []options.Option
|
||||||
nopts = append(nopts, v4.HandlerEndpoints(MeterServiceServerEndpoints))
|
nopts = append(nopts, v4.HandlerEndpoints(MeterServiceServerEndpoints))
|
||||||
return s.Handle(s.NewHandler(&MeterService{h}, append(nopts, opts...)...))
|
return s.Handle(&MeterService{h}, append(nopts, opts...)...)
|
||||||
}
|
}
|
||||||
|
49
handler/meter/meter_test.go
Normal file
49
handler/meter/meter_test.go
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
package meter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
codecpb "go.unistack.org/micro-proto/v4/codec"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHandler_Metrics(t *testing.T) {
|
||||||
|
type fields struct {
|
||||||
|
opts Options
|
||||||
|
}
|
||||||
|
type args struct {
|
||||||
|
ctx context.Context
|
||||||
|
req *codecpb.Frame
|
||||||
|
rsp *codecpb.Frame
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
fields fields
|
||||||
|
args args
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"Test #1",
|
||||||
|
fields{
|
||||||
|
opts: NewOptions(),
|
||||||
|
},
|
||||||
|
args{
|
||||||
|
context.Background(),
|
||||||
|
&codecpb.Frame{Data: []byte("gzip")},
|
||||||
|
&codecpb.Frame{},
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
h := &Handler{
|
||||||
|
opts: tt.fields.opts,
|
||||||
|
}
|
||||||
|
if err := h.Metrics(tt.args.ctx, tt.args.req, tt.args.rsp); (err != nil) != tt.wantErr {
|
||||||
|
t.Errorf("Metrics() error = %v, wantErr %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
t.Logf("RSP: %v", tt.args.rsp.Data)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
19
handler/spa/spa.go
Normal file
19
handler/spa/spa.go
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package spa
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handler serve files from dir and redirect to index if file not exists
|
||||||
|
var Handler = func(prefix string, dir fs.FS) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f := http.StripPrefix(prefix, http.FileServer(http.FS(dir)))
|
||||||
|
if _, err := fs.Stat(dir, strings.TrimPrefix(r.RequestURI, prefix)); err != nil {
|
||||||
|
r.RequestURI = prefix
|
||||||
|
r.URL.Path = prefix
|
||||||
|
}
|
||||||
|
f.ServeHTTP(w, r)
|
||||||
|
}
|
||||||
|
}
|
@ -1,20 +0,0 @@
|
|||||||
window.onload = function() {
|
|
||||||
//<editor-fold desc="Changeable Configuration Block">
|
|
||||||
|
|
||||||
// the following lines will be replaced by docker/configurator, when it runs in a docker-container
|
|
||||||
window.ui = SwaggerUIBundle({
|
|
||||||
url: "{{ .SWAGGER }}",
|
|
||||||
dom_id: '#swagger-ui',
|
|
||||||
deepLinking: true,
|
|
||||||
presets: [
|
|
||||||
SwaggerUIBundle.presets.apis,
|
|
||||||
SwaggerUIStandalonePreset
|
|
||||||
],
|
|
||||||
plugins: [
|
|
||||||
SwaggerUIBundle.plugins.DownloadUrl
|
|
||||||
],
|
|
||||||
layout: "StandaloneLayout"
|
|
||||||
});
|
|
||||||
|
|
||||||
//</editor-fold>
|
|
||||||
};
|
|
61
handler/swagger/swagger.go
Normal file
61
handler/swagger/swagger.go
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
package swagger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
yamlcodec "go.unistack.org/micro-codec-yaml/v4"
|
||||||
|
rutil "go.unistack.org/micro/v4/util/reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handler append to generated swagger data from dst map[string]interface{}
|
||||||
|
var Handler = func(dst map[string]interface{}, fsys fs.FS) http.HandlerFunc {
|
||||||
|
c := yamlcodec.NewCodec()
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path := r.URL.Path
|
||||||
|
if len(path) > 1 && path[0] == '/' {
|
||||||
|
path = path[1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
buf, err := fs.ReadFile(fsys, path)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
_, _ = w.Write([]byte(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if dst == nil {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write(buf)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var src interface{}
|
||||||
|
|
||||||
|
if err = c.Unmarshal(buf, src); err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
_, _ = w.Write([]byte(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = rutil.Merge(src, dst); err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
_, _ = w.Write([]byte(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf, err = c.Marshal(src); err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
_, _ = w.Write([]byte(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write(buf)
|
||||||
|
}
|
||||||
|
}
|
133
http.go
133
http.go
@ -15,6 +15,7 @@ import (
|
|||||||
|
|
||||||
"go.unistack.org/micro/v4/codec"
|
"go.unistack.org/micro/v4/codec"
|
||||||
"go.unistack.org/micro/v4/logger"
|
"go.unistack.org/micro/v4/logger"
|
||||||
|
"go.unistack.org/micro/v4/options"
|
||||||
"go.unistack.org/micro/v4/register"
|
"go.unistack.org/micro/v4/register"
|
||||||
"go.unistack.org/micro/v4/server"
|
"go.unistack.org/micro/v4/server"
|
||||||
rhttp "go.unistack.org/micro/v4/util/http"
|
rhttp "go.unistack.org/micro/v4/util/http"
|
||||||
@ -24,11 +25,11 @@ import (
|
|||||||
var _ server.Server = (*Server)(nil)
|
var _ server.Server = (*Server)(nil)
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
hd server.Handler
|
hd interface{}
|
||||||
rsvc *register.Service
|
rsvc *register.Service
|
||||||
handlers map[string]server.Handler
|
handlers map[string]interface{}
|
||||||
exit chan chan error
|
exit chan chan error
|
||||||
errorHandler func(context.Context, server.Handler, http.ResponseWriter, *http.Request, error, int)
|
errorHandler func(context.Context, interface{}, http.ResponseWriter, *http.Request, error, int)
|
||||||
pathHandlers *rhttp.Trie
|
pathHandlers *rhttp.Trie
|
||||||
opts server.Options
|
opts server.Options
|
||||||
registerRPC bool
|
registerRPC bool
|
||||||
@ -57,7 +58,7 @@ func (h *Server) Options() server.Options {
|
|||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Server) Init(opts ...server.Option) error {
|
func (h *Server) Init(opts ...options.Option) error {
|
||||||
if len(opts) == 0 && h.init {
|
if len(opts) == 0 && h.init {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -67,11 +68,11 @@ func (h *Server) Init(opts ...server.Option) error {
|
|||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&h.opts)
|
o(&h.opts)
|
||||||
}
|
}
|
||||||
if fn, ok := h.opts.Context.Value(errorHandlerKey{}).(func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int)); ok && fn != nil {
|
if fn, ok := h.opts.Context.Value(errorHandlerKey{}).(func(ctx context.Context, s interface{}, w http.ResponseWriter, r *http.Request, err error, status int)); ok && fn != nil {
|
||||||
h.errorHandler = fn
|
h.errorHandler = fn
|
||||||
}
|
}
|
||||||
if h.handlers == nil {
|
if h.handlers == nil {
|
||||||
h.handlers = make(map[string]server.Handler)
|
h.handlers = make(map[string]interface{})
|
||||||
}
|
}
|
||||||
if h.pathHandlers == nil {
|
if h.pathHandlers == nil {
|
||||||
h.pathHandlers = rhttp.NewTrie()
|
h.pathHandlers = rhttp.NewTrie()
|
||||||
@ -110,10 +111,6 @@ func (h *Server) Init(opts ...server.Option) error {
|
|||||||
h.RUnlock()
|
h.RUnlock()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := h.opts.Transport.Init(); err != nil {
|
|
||||||
h.RUnlock()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
h.RUnlock()
|
h.RUnlock()
|
||||||
|
|
||||||
h.Lock()
|
h.Lock()
|
||||||
@ -123,12 +120,24 @@ func (h *Server) Init(opts ...server.Option) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Server) Handle(handler server.Handler) error {
|
func (h *Server) Handle(handler interface{}, opts ...options.Option) error {
|
||||||
|
options := server.NewHandleOptions(opts...)
|
||||||
|
var endpointMetadata []EndpointMetadata
|
||||||
|
|
||||||
|
if v, ok := options.Context.Value(handlerEndpointsKey{}).([]EndpointMetadata); ok {
|
||||||
|
endpointMetadata = v
|
||||||
|
}
|
||||||
|
|
||||||
// passed unknown handler
|
// passed unknown handler
|
||||||
hdlr, ok := handler.(*httpHandler)
|
hdlr, ok := handler.(*httpHandler)
|
||||||
if !ok {
|
if !ok {
|
||||||
h.Lock()
|
h.Lock()
|
||||||
h.hd = handler
|
if h.handlers == nil {
|
||||||
|
h.handlers = make(map[string]interface{})
|
||||||
|
}
|
||||||
|
for _, v := range endpointMetadata {
|
||||||
|
h.handlers[v.Name] = h.newHTTPHandler(handler, opts...)
|
||||||
|
}
|
||||||
h.Unlock()
|
h.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -141,19 +150,11 @@ func (h *Server) Handle(handler server.Handler) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// passed micro compat handler
|
|
||||||
h.Lock()
|
|
||||||
if h.handlers == nil {
|
|
||||||
h.handlers = make(map[string]server.Handler)
|
|
||||||
}
|
|
||||||
h.handlers[handler.Name()] = handler
|
|
||||||
h.Unlock()
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) server.Handler {
|
func (h *Server) newHTTPHandler(handler interface{}, opts ...options.Option) *httpHandler {
|
||||||
options := server.NewHandlerOptions(opts...)
|
options := server.NewHandleOptions(opts...)
|
||||||
|
|
||||||
eps := make([]*register.Endpoint, 0, len(options.Metadata))
|
eps := make([]*register.Endpoint, 0, len(options.Metadata))
|
||||||
for name, metadata := range options.Metadata {
|
for name, metadata := range options.Metadata {
|
||||||
@ -197,16 +198,16 @@ func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) s
|
|||||||
}
|
}
|
||||||
|
|
||||||
if method.Name == "" && h.opts.Logger.V(logger.ErrorLevel) {
|
if method.Name == "" && h.opts.Logger.V(logger.ErrorLevel) {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "nil method for %s", mname)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil method for %s", mname))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
mtype, err := prepareEndpoint(method)
|
mtype, err := prepareEndpoint(method)
|
||||||
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
|
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "%v", err)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("%v", err))
|
||||||
continue
|
continue
|
||||||
} else if mtype == nil {
|
} else if mtype == nil {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "nil mtype for %s", mname)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil mtype for %s", mname))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -217,13 +218,13 @@ func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) s
|
|||||||
hdlr.name = name
|
hdlr.name = name
|
||||||
|
|
||||||
if err := hdlr.handlers.Insert([]string{md["Method"]}, md["Path"], pth); err != nil {
|
if err := hdlr.handlers.Insert([]string{md["Method"]}, md["Path"], pth); err != nil {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "cant add handler for %s %s", md["Method"], md["Path"])
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add handler for %s %s", md["Method"][0], md["Path"][0]))
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.registerRPC {
|
if h.registerRPC {
|
||||||
h.opts.Logger.Infof(h.opts.Context, "register rpc handler for http.MethodPost %s /%s", hn, hn)
|
h.opts.Logger.Info(h.opts.Context, fmt.Sprintf("register rpc handler for http.MethodPost %s /%s", hn, hn))
|
||||||
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {
|
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "cant add rpc handler for http.MethodPost %s /%s", hn, hn)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add rpc handler for http.MethodPost %s /%s", hn, hn))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -247,16 +248,16 @@ func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) s
|
|||||||
}
|
}
|
||||||
|
|
||||||
if method.Name == "" && h.opts.Logger.V(logger.ErrorLevel) {
|
if method.Name == "" && h.opts.Logger.V(logger.ErrorLevel) {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "nil method for %s", mname)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil method for %s", mname))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
mtype, err := prepareEndpoint(method)
|
mtype, err := prepareEndpoint(method)
|
||||||
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
|
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "%v", err)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("%v", err))
|
||||||
continue
|
continue
|
||||||
} else if mtype == nil {
|
} else if mtype == nil {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "nil mtype for %s", mname)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil mtype for %s", mname))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -267,13 +268,13 @@ func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) s
|
|||||||
hdlr.name = name
|
hdlr.name = name
|
||||||
|
|
||||||
if err := hdlr.handlers.Insert([]string{md.Method}, md.Path, pth); err != nil {
|
if err := hdlr.handlers.Insert([]string{md.Method}, md.Path, pth); err != nil {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "cant add handler for %s %s", md.Method, md.Path)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add handler for %s %s", md.Method, md.Path))
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.registerRPC {
|
if h.registerRPC {
|
||||||
h.opts.Logger.Infof(h.opts.Context, "register rpc handler for http.MethodPost %s /%s", hn, hn)
|
h.opts.Logger.Info(h.opts.Context, fmt.Sprintf("register rpc handler for http.MethodPost %s /%s", hn, hn))
|
||||||
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {
|
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {
|
||||||
h.opts.Logger.Errorf(h.opts.Context, "cant add rpc handler for http.MethodPost %s /%s", hn, hn)
|
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add rpc handler for http.MethodPost %s /%s", hn, hn))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -285,7 +286,11 @@ func (h *Server) Register() error {
|
|||||||
var eps []*register.Endpoint
|
var eps []*register.Endpoint
|
||||||
h.RLock()
|
h.RLock()
|
||||||
for _, hdlr := range h.handlers {
|
for _, hdlr := range h.handlers {
|
||||||
eps = append(eps, hdlr.Endpoints()...)
|
hd, ok := hdlr.(*httpHandler)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
eps = append(eps, hd.Endpoints()...)
|
||||||
}
|
}
|
||||||
rsvc := h.rsvc
|
rsvc := h.rsvc
|
||||||
config := h.opts
|
config := h.opts
|
||||||
@ -303,7 +308,7 @@ func (h *Server) Register() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
service.Nodes[0].Metadata["protocol"] = "http"
|
service.Nodes[0].Metadata.Set("protocol", "http")
|
||||||
service.Endpoints = eps
|
service.Endpoints = eps
|
||||||
|
|
||||||
h.RLock()
|
h.RLock()
|
||||||
@ -312,7 +317,7 @@ func (h *Server) Register() error {
|
|||||||
|
|
||||||
if !registered {
|
if !registered {
|
||||||
if config.Logger.V(logger.InfoLevel) {
|
if config.Logger.V(logger.InfoLevel) {
|
||||||
config.Logger.Infof(config.Context, "Register [%s] Registering node: %s", config.Register.String(), service.Nodes[0].ID)
|
config.Logger.Info(config.Context, fmt.Sprintf("Register [%s] Registering node: %s", config.Register.String(), service.Nodes[0].ID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -345,7 +350,7 @@ func (h *Server) Deregister() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if config.Logger.V(logger.InfoLevel) {
|
if config.Logger.V(logger.InfoLevel) {
|
||||||
config.Logger.Infof(config.Context, "Deregistering node: %s", service.Nodes[0].ID)
|
config.Logger.Info(config.Context, fmt.Sprintf("Deregistering node: %s", service.Nodes[0].ID))
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := server.DefaultDeregisterFunc(service, config); err != nil {
|
if err := server.DefaultDeregisterFunc(service, config); err != nil {
|
||||||
@ -395,7 +400,7 @@ func (h *Server) Start() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if config.Logger.V(logger.InfoLevel) {
|
if config.Logger.V(logger.InfoLevel) {
|
||||||
config.Logger.Infof(config.Context, "Listening on %s", ts.Addr().String())
|
config.Logger.Info(config.Context, fmt.Sprintf("Listening on %s", ts.Addr().String()))
|
||||||
}
|
}
|
||||||
|
|
||||||
h.Lock()
|
h.Lock()
|
||||||
@ -403,13 +408,12 @@ func (h *Server) Start() error {
|
|||||||
h.Unlock()
|
h.Unlock()
|
||||||
|
|
||||||
var handler http.Handler
|
var handler http.Handler
|
||||||
var srvFunc func(net.Listener) error
|
|
||||||
|
|
||||||
// nolint: nestif
|
// nolint: nestif
|
||||||
if h.opts.Context != nil {
|
if h.opts.Context != nil {
|
||||||
if hs, ok := h.opts.Context.Value(serverKey{}).(*http.Server); ok && hs != nil {
|
if hs, ok := h.opts.Context.Value(serverKey{}).(*http.Server); ok && hs != nil {
|
||||||
if hs.Handler == nil && h.hd != nil {
|
if hs.Handler == nil && h.hd != nil {
|
||||||
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
|
if hdlr, ok := h.hd.(http.Handler); ok {
|
||||||
hs.Handler = hdlr
|
hs.Handler = hdlr
|
||||||
handler = hs.Handler
|
handler = hs.Handler
|
||||||
}
|
}
|
||||||
@ -425,7 +429,7 @@ func (h *Server) Start() error {
|
|||||||
case len(h.handlers) > 0 && h.hd != nil:
|
case len(h.handlers) > 0 && h.hd != nil:
|
||||||
handler = h
|
handler = h
|
||||||
case handler == nil && h.hd != nil:
|
case handler == nil && h.hd != nil:
|
||||||
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
|
if hdlr, ok := h.hd.(http.Handler); ok {
|
||||||
handler = hdlr
|
handler = hdlr
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -436,7 +440,7 @@ func (h *Server) Start() error {
|
|||||||
|
|
||||||
if err := config.RegisterCheck(h.opts.Context); err != nil {
|
if err := config.RegisterCheck(h.opts.Context); err != nil {
|
||||||
if config.Logger.V(logger.ErrorLevel) {
|
if config.Logger.V(logger.ErrorLevel) {
|
||||||
config.Logger.Errorf(config.Context, "Server %s-%s register check error: %s", config.Name, config.ID, err)
|
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register check error: %s", config.Name, config.ID, err))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if err = h.Register(); err != nil {
|
if err = h.Register(); err != nil {
|
||||||
@ -446,6 +450,7 @@ func (h *Server) Start() error {
|
|||||||
|
|
||||||
fn := handler
|
fn := handler
|
||||||
|
|
||||||
|
var hs *http.Server
|
||||||
if h.opts.Context != nil {
|
if h.opts.Context != nil {
|
||||||
if mwf, ok := h.opts.Context.Value(middlewareKey{}).([]func(http.Handler) http.Handler); ok && len(mwf) > 0 {
|
if mwf, ok := h.opts.Context.Value(middlewareKey{}).([]func(http.Handler) http.Handler); ok && len(mwf) > 0 {
|
||||||
// wrap the handler func
|
// wrap the handler func
|
||||||
@ -453,25 +458,19 @@ func (h *Server) Start() error {
|
|||||||
fn = mwf[i-1](fn)
|
fn = mwf[i-1](fn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if hs, ok := h.opts.Context.Value(serverKey{}).(*http.Server); ok && hs != nil {
|
var ok bool
|
||||||
|
if hs, ok = h.opts.Context.Value(serverKey{}).(*http.Server); ok && hs != nil {
|
||||||
hs.Handler = fn
|
hs.Handler = fn
|
||||||
srvFunc = hs.Serve
|
} else {
|
||||||
|
hs = &http.Server{Handler: fn}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if srvFunc != nil {
|
|
||||||
go func() {
|
go func() {
|
||||||
if cerr := srvFunc(ts); cerr != nil && !errors.Is(cerr, net.ErrClosed) {
|
if cerr := hs.Serve(ts); cerr != nil && !errors.Is(cerr, net.ErrClosed) {
|
||||||
h.opts.Logger.Error(h.opts.Context, cerr)
|
h.opts.Logger.Error(h.opts.Context, cerr.Error())
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
} else {
|
|
||||||
go func() {
|
|
||||||
if cerr := http.Serve(ts, fn); cerr != nil && !errors.Is(cerr, net.ErrClosed) {
|
|
||||||
h.opts.Logger.Error(h.opts.Context, cerr)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
t := new(time.Ticker)
|
t := new(time.Ticker)
|
||||||
@ -497,28 +496,28 @@ func (h *Server) Start() error {
|
|||||||
// nolint: nestif
|
// nolint: nestif
|
||||||
if rerr != nil && registered {
|
if rerr != nil && registered {
|
||||||
if config.Logger.V(logger.ErrorLevel) {
|
if config.Logger.V(logger.ErrorLevel) {
|
||||||
config.Logger.Errorf(config.Context, "Server %s-%s register check error: %s, deregister it", config.Name, config.ID, rerr)
|
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register check error: %s, deregister it", config.Name, config.ID, rerr))
|
||||||
}
|
}
|
||||||
// deregister self in case of error
|
// deregister self in case of error
|
||||||
if err := h.Deregister(); err != nil {
|
if err := h.Deregister(); err != nil {
|
||||||
if config.Logger.V(logger.ErrorLevel) {
|
if config.Logger.V(logger.ErrorLevel) {
|
||||||
config.Logger.Errorf(config.Context, "Server %s-%s deregister error: %s", config.Name, config.ID, err)
|
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s deregister error: %s", config.Name, config.ID, err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if rerr != nil && !registered {
|
} else if rerr != nil && !registered {
|
||||||
if config.Logger.V(logger.ErrorLevel) {
|
if config.Logger.V(logger.ErrorLevel) {
|
||||||
config.Logger.Errorf(config.Context, "Server %s-%s register check error: %s", config.Name, config.ID, rerr)
|
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register check error: %s", config.Name, config.ID, rerr))
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if err := h.Register(); err != nil {
|
if err := h.Register(); err != nil {
|
||||||
if config.Logger.V(logger.ErrorLevel) {
|
if config.Logger.V(logger.ErrorLevel) {
|
||||||
config.Logger.Errorf(config.Context, "Server %s-%s register error: %s", config.Name, config.ID, err)
|
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register error: %s", config.Name, config.ID, err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.Register(); err != nil {
|
if err := h.Register(); err != nil {
|
||||||
config.Logger.Errorf(config.Context, "Server register error: %s", err)
|
config.Logger.Error(config.Context, fmt.Sprintf("Server register error: %s", err))
|
||||||
}
|
}
|
||||||
// wait for exit
|
// wait for exit
|
||||||
case ch = <-h.exit:
|
case ch = <-h.exit:
|
||||||
@ -528,10 +527,18 @@ func (h *Server) Start() error {
|
|||||||
|
|
||||||
// deregister
|
// deregister
|
||||||
if err := h.Deregister(); err != nil {
|
if err := h.Deregister(); err != nil {
|
||||||
config.Logger.Errorf(config.Context, "Server deregister error: %s", err)
|
config.Logger.Error(config.Context, fmt.Sprintf("Server deregister error: %s", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
ch <- ts.Close()
|
ctx, cancel := context.WithTimeout(context.Background(), h.opts.GracefulTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
err := hs.Shutdown(ctx)
|
||||||
|
if err != nil {
|
||||||
|
err = hs.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
ch <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@ -551,7 +558,7 @@ func (h *Server) Name() string {
|
|||||||
return h.opts.Name
|
return h.opts.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(opts ...server.Option) *Server {
|
func NewServer(opts ...options.Option) *Server {
|
||||||
options := server.NewOptions(opts...)
|
options := server.NewOptions(opts...)
|
||||||
eh := DefaultErrorHandler
|
eh := DefaultErrorHandler
|
||||||
if v, ok := options.Context.Value(errorHandlerKey{}).(errorHandler); ok && v != nil {
|
if v, ok := options.Context.Value(errorHandlerKey{}).(errorHandler); ok && v != nil {
|
||||||
|
43
options.go
43
options.go
@ -5,7 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"go.unistack.org/micro/v4/server"
|
"go.unistack.org/micro/v4/options"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SetError pass error to caller
|
// SetError pass error to caller
|
||||||
@ -79,24 +79,24 @@ func GetRspCode(ctx context.Context) int {
|
|||||||
type middlewareKey struct{}
|
type middlewareKey struct{}
|
||||||
|
|
||||||
// Middleware passes http middlewares
|
// Middleware passes http middlewares
|
||||||
func Middleware(mw ...func(http.Handler) http.Handler) server.Option {
|
func Middleware(mw ...func(http.Handler) http.Handler) options.Option {
|
||||||
return server.SetOption(middlewareKey{}, mw)
|
return options.ContextOption(middlewareKey{}, mw)
|
||||||
}
|
}
|
||||||
|
|
||||||
type serverKey struct{}
|
type serverKey struct{}
|
||||||
|
|
||||||
// HTTPServer provide ability to pass *http.Server
|
// HTTPServer provide ability to pass *http.Server
|
||||||
func HTTPServer(hs *http.Server) server.Option {
|
func HTTPServer(hs *http.Server) options.Option {
|
||||||
return server.SetOption(serverKey{}, hs)
|
return options.ContextOption(serverKey{}, hs)
|
||||||
}
|
}
|
||||||
|
|
||||||
type errorHandler func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int)
|
type errorHandler func(ctx context.Context, s interface{}, w http.ResponseWriter, r *http.Request, err error, status int)
|
||||||
|
|
||||||
type errorHandlerKey struct{}
|
type errorHandlerKey struct{}
|
||||||
|
|
||||||
// ErrorHandler specifies handler for errors
|
// ErrorHandler specifies handler for errors
|
||||||
func ErrorHandler(fn errorHandler) server.Option {
|
func ErrorHandler(fn errorHandler) options.Option {
|
||||||
return server.SetOption(errorHandlerKey{}, fn)
|
return options.ContextOption(errorHandlerKey{}, fn)
|
||||||
}
|
}
|
||||||
|
|
||||||
type (
|
type (
|
||||||
@ -107,12 +107,18 @@ type (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// PathHandler specifies http handler for path regexp
|
// PathHandler specifies http handler for path regexp
|
||||||
func PathHandler(method, path string, handler http.HandlerFunc) server.Option {
|
func PathHandler(method, path string, handler http.HandlerFunc) options.Option {
|
||||||
return func(o *server.Options) {
|
return func(src interface{}) error {
|
||||||
if o.Context == nil {
|
vctx, err := options.Get(src, ".Context")
|
||||||
o.Context = context.Background()
|
if err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
v, ok := o.Context.Value(pathHandlerKey{}).(*pathHandlerVal)
|
ctx, ok := vctx.(context.Context)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid option")
|
||||||
|
}
|
||||||
|
|
||||||
|
v, ok := ctx.Value(pathHandlerKey{}).(*pathHandlerVal)
|
||||||
if !ok {
|
if !ok {
|
||||||
v = &pathHandlerVal{h: make(map[string]map[string]http.HandlerFunc)}
|
v = &pathHandlerVal{h: make(map[string]map[string]http.HandlerFunc)}
|
||||||
}
|
}
|
||||||
@ -121,16 +127,17 @@ func PathHandler(method, path string, handler http.HandlerFunc) server.Option {
|
|||||||
m = make(map[string]http.HandlerFunc)
|
m = make(map[string]http.HandlerFunc)
|
||||||
v.h[method] = m
|
v.h[method] = m
|
||||||
}
|
}
|
||||||
|
ctx = context.WithValue(ctx, pathHandlerKey{}, v)
|
||||||
m[path] = handler
|
m[path] = handler
|
||||||
o.Context = context.WithValue(o.Context, pathHandlerKey{}, v)
|
return options.Set(src, ctx, ".Context")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type registerRPCHandlerKey struct{}
|
type registerRPCHandlerKey struct{}
|
||||||
|
|
||||||
// RegisterRPCHandler registers compatibility endpoints with /ServiceName.ServiceEndpoint method POST
|
// RegisterRPCHandler registers compatibility endpoints with /ServiceName.ServiceEndpoint method POST
|
||||||
func RegisterRPCHandler(b bool) server.Option {
|
func RegisterRPCHandler(b bool) options.Option {
|
||||||
return server.SetOption(registerRPCHandlerKey{}, b)
|
return options.ContextOption(registerRPCHandlerKey{}, b)
|
||||||
}
|
}
|
||||||
|
|
||||||
type handlerEndpointsKey struct{}
|
type handlerEndpointsKey struct{}
|
||||||
@ -143,8 +150,8 @@ type EndpointMetadata struct {
|
|||||||
Stream bool
|
Stream bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandlerEndpoints(md []EndpointMetadata) server.HandlerOption {
|
func HandlerEndpoints(md []EndpointMetadata) options.Option {
|
||||||
return server.SetHandlerOption(handlerEndpointsKey{}, md)
|
return options.ContextOption(handlerEndpointsKey{}, md)
|
||||||
}
|
}
|
||||||
|
|
||||||
type handlerOptions struct {
|
type handlerOptions struct {
|
||||||
|
8
tools.go
Normal file
8
tools.go
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
//go:build tools
|
||||||
|
|
||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "go.unistack.org/micro-proto/v4"
|
||||||
|
_ "go.unistack.org/protoc-gen-go-micro/v4"
|
||||||
|
)
|
8
util.go
8
util.go
@ -31,15 +31,13 @@ func FillRequest(ctx context.Context, req interface{}, opts ...FillRequestOption
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cookies := strings.Split(md["Cookie"], ";")
|
cookies := md["Cookie"]
|
||||||
cmd := make(map[string]string, len(cookies))
|
cmd := make(map[string]string, len(cookies))
|
||||||
for _, cookie := range cookies {
|
kv := strings.Split(cookies, "=")
|
||||||
kv := strings.Split(cookie, "=")
|
|
||||||
if len(kv) != 2 {
|
if len(kv) != 2 {
|
||||||
continue
|
return nil
|
||||||
}
|
}
|
||||||
cmd[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
|
cmd[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
|
||||||
}
|
|
||||||
for idx := 0; idx < len(options.cookies)/2; idx += 2 {
|
for idx := 0; idx < len(options.cookies)/2; idx += 2 {
|
||||||
k := http.CanonicalHeaderKey(options.cookies[idx])
|
k := http.CanonicalHeaderKey(options.cookies[idx])
|
||||||
v, ok := cmd[k]
|
v, ok := cmd[k]
|
||||||
|
Loading…
Reference in New Issue
Block a user