Compare commits

..

2 Commits
master ... tls

Author SHA1 Message Date
32e7875fab add tls headers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-08-03 10:44:26 +03:00
93a0af7cde add tls headers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2023-08-03 10:40:02 +03:00
17 changed files with 230 additions and 1830 deletions

24
.gitignore vendored
View File

@ -1,24 +0,0 @@
# 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

24
go.mod
View File

@ -3,23 +3,17 @@ module go.unistack.org/micro-server-http/v4
go 1.19
require (
go.unistack.org/micro-codec-yaml/v4 v4.0.0
go.unistack.org/micro-proto/v4 v4.0.1
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
go.unistack.org/micro-proto/v4 v4.0.0
go.unistack.org/micro/v4 v4.0.1
golang.org/x/net v0.10.0
)
require (
github.com/fatih/structtag v1.2.0 // indirect
github.com/golang/protobuf v1.5.4 // 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
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/gnostic v0.6.9 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/kr/text v0.2.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
)

1433
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -19,10 +19,10 @@ import (
)
var (
DefaultErrorHandler = func(ctx context.Context, s interface{}, w http.ResponseWriter, r *http.Request, err error, status int) {
DefaultErrorHandler = func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int) {
w.WriteHeader(status)
if _, cerr := w.Write([]byte(err.Error())); cerr != nil {
logger.DefaultLogger.Error(ctx, fmt.Sprintf("write failed: %v", cerr))
logger.DefaultLogger.Errorf(ctx, "write failed: %v", cerr)
}
}
DefaultContentType = "application/json"
@ -35,7 +35,7 @@ type patHandler struct {
}
type httpHandler struct {
opts server.HandleOptions
opts server.HandlerOptions
hd interface{}
handlers *rhttp.Trie
name string
@ -56,7 +56,7 @@ func (h *httpHandler) Endpoints() []*register.Endpoint {
return h.eps
}
func (h *httpHandler) Options() server.HandleOptions {
func (h *httpHandler) Options() server.HandlerOptions {
return h.opts
}
@ -109,22 +109,21 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
md = metadata.New(len(r.Header) + 8)
}
for k, v := range r.Header {
md[k] = v[0]
md[k] = strings.Join(v, ", ")
}
md["RemoteAddr"] = r.RemoteAddr
md["Method"] = r.Method
md["URL"] = r.URL.String()
md["Proto"] = r.Proto
md["Content-Length"] = fmt.Sprintf("%d", r.ContentLength)
md["Transfer-Encoding"] = r.TransferEncoding[0]
md["ContentLength"] = fmt.Sprintf("%d", r.ContentLength)
md["TransferEncoding"] = strings.Join(r.TransferEncoding, ",")
md["Host"] = r.Host
md["RequestURI"] = r.RequestURI
if r.TLS != nil {
md["TLS"] = "true"
md["TLS-ALPN"] = r.TLS.NegotiatedProtocol
md["TLS-ServerName"] = r.TLS.ServerName
md["TLS_ALPN"] = r.TLS.NegotiatedProtocol
md["TLS_ServerName"] = r.TLS.ServerName
}
ctx = metadata.NewIncomingContext(ctx, md)
path := r.URL.Path
@ -263,17 +262,18 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
}
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
for k, v := range nmd {
md[k] = v
md.Set(k, v)
}
}
metadata.SetOutgoingContext(ctx, md)
return err
}
// wrap the handler func
// for i := len(handler.sopts.Hooks); i > 0; i-- {
// fn = handler.sopts.Hooks[i-1](fn)
// }
for i := len(handler.sopts.HdlrWrappers); i > 0; i-- {
fn = handler.sopts.HdlrWrappers[i-1](fn)
}
if ct == "application/x-www-form-urlencoded" {
cf, err = h.newCodec(DefaultContentType)
@ -290,12 +290,14 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
w.Header().Set(metadata.HeaderContentType, ct)
if md, ok := metadata.FromOutgoingContext(ctx); ok {
for k, v := range md {
w.Header()[k] = []string{v}
w.Header().Set(k, v)
}
}
if md := getRspHeader(ctx); md != nil {
for k, v := range md {
w.Header()[k] = v
for _, vv := range v {
w.Header().Add(k, vv)
}
}
}
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
@ -321,7 +323,7 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
}
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
handler.sopts.Logger.Error(handler.sopts.Context, fmt.Sprintf("handler err: %v", err))
handler.sopts.Logger.Errorf(handler.sopts.Context, "handler err: %v", err)
return
}
@ -331,7 +333,7 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
w.WriteHeader(scode)
if _, cerr := w.Write(buf); cerr != nil {
handler.sopts.Logger.Error(ctx, fmt.Sprintf("write failed: %v", cerr))
handler.sopts.Logger.Errorf(ctx, "write failed: %v", cerr)
}
}, nil
}
@ -349,7 +351,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
md = metadata.New(len(r.Header) + 8)
}
for k, v := range r.Header {
md[k] = v[0]
md[k] = strings.Join(v, ", ")
}
md["RemoteAddr"] = r.RemoteAddr
if r.TLS != nil {
@ -360,9 +362,9 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
md["Method"] = r.Method
md["URL"] = r.URL.String()
md["Proto"] = r.Proto
md["Content-Length"] = fmt.Sprintf("%d", r.ContentLength)
md["ContentLength"] = fmt.Sprintf("%d", r.ContentLength)
if len(r.TransferEncoding) > 0 {
md["Transfer-Encoding"] = r.TransferEncoding[0]
md["TransferEncoding"] = strings.Join(r.TransferEncoding, ",")
}
md["Host"] = r.Host
md["RequestURI"] = r.RequestURI
@ -419,7 +421,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if !match && h.hd != nil {
if hdlr, ok := h.hd.(http.Handler); ok {
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
hdlr.ServeHTTP(w, r)
return
}
@ -523,17 +525,18 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
for k, v := range nmd {
md[k] = v
md.Set(k, v)
}
}
metadata.SetOutgoingContext(ctx, md)
return err
}
// wrap the handler func
// for i := len(handler.sopts.HdlrWrappers); i > 0; i-- {
// fn = handler.sopts.HdlrWrappers[i-1](fn)
// }
for i := len(handler.sopts.HdlrWrappers); i > 0; i-- {
fn = handler.sopts.HdlrWrappers[i-1](fn)
}
if ct == "application/x-www-form-urlencoded" {
cf, err = h.newCodec(DefaultContentType)
@ -550,7 +553,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set(metadata.HeaderContentType, ct)
if md, ok := metadata.FromOutgoingContext(ctx); ok {
for k, v := range md {
w.Header()[k] = []string{v}
w.Header().Set(k, v)
}
}
if md := getRspHeader(ctx); md != nil {
@ -583,7 +586,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if err != nil && handler.sopts.Logger.V(logger.ErrorLevel) {
handler.sopts.Logger.Error(handler.sopts.Context, fmt.Sprintf("handler err: %v", err))
handler.sopts.Logger.Errorf(handler.sopts.Context, "handler err: %v", err)
return
}
@ -593,6 +596,6 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(scode)
if _, cerr := w.Write(buf); cerr != nil {
handler.sopts.Logger.Error(ctx, fmt.Sprintf("write failed: %v", cerr))
handler.sopts.Logger.Errorf(ctx, "write failed: %v", cerr)
}
}

View File

@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
// versions:
// - protoc-gen-go-micro v4.0.2
// - protoc v4.23.4
// - protoc-gen-go-micro v4.0.0
// - protoc v3.21.12
// source: health/health.proto
package health
@ -9,11 +9,37 @@ package health
import (
context "context"
codec "go.unistack.org/micro-proto/v4/codec"
v4 "go.unistack.org/micro-server-http/v4"
)
var (
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 {
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error

View File

@ -1,5 +1,5 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v4.0.2
// protoc-gen-go-micro version: v4.0.0
// source: health/health.proto
package health
@ -8,36 +8,9 @@ import (
context "context"
codec "go.unistack.org/micro-proto/v4/codec"
v4 "go.unistack.org/micro-server-http/v4"
options "go.unistack.org/micro/v4/options"
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 {
HealthServiceServer
}
@ -54,7 +27,7 @@ func (h *healthServiceServer) Version(ctx context.Context, req *codec.Frame, rsp
return h.HealthServiceServer.Version(ctx, req, rsp)
}
func RegisterHealthServiceServer(s server.Server, sh HealthServiceServer, opts ...options.Option) error {
func RegisterHealthServiceServer(s server.Server, sh HealthServiceServer, opts ...server.HandlerOption) error {
type healthService interface {
Live(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
Ready(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
@ -64,7 +37,7 @@ func RegisterHealthServiceServer(s server.Server, sh HealthServiceServer, opts .
healthService
}
h := &healthServiceServer{sh}
var nopts []options.Option
var nopts []server.HandlerOption
nopts = append(nopts, v4.HandlerEndpoints(HealthServiceServerEndpoints))
return s.Handle(&HealthService{h}, append(nopts, opts...)...)
return s.Handle(s.NewHandler(&HealthService{h}, append(nopts, opts...)...))
}

View File

@ -2,36 +2,13 @@ package meter // import "go.unistack.org/micro-server-http/v4/handler/meter"
import (
"bytes"
"compress/gzip"
"context"
"io"
"strings"
"sync"
codecpb "go.unistack.org/micro-proto/v4/codec"
"go.unistack.org/micro/v4/logger"
"go.unistack.org/micro/v4/metadata"
"go.unistack.org/micro/v4/errors"
"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
var _ MeterServiceServer = (*Handler)(nil)
@ -44,8 +21,7 @@ type Option func(*Options)
type Options struct {
Meter meter.Meter
Name string
MeterOptions []options.Option
DisableCompress bool
MeterOptions []meter.Option
}
func Meter(m meter.Meter) Option {
@ -60,20 +36,14 @@ func Name(name string) Option {
}
}
func DisableCompress(g bool) Option {
return func(o *Options) {
o.DisableCompress = g
}
}
func MeterOptions(opts ...options.Option) Option {
func MeterOptions(opts ...meter.Option) Option {
return func(o *Options) {
o.MeterOptions = append(o.MeterOptions, opts...)
}
}
func NewOptions(opts ...Option) Options {
options := Options{Meter: meter.DefaultMeter, DisableCompress: false}
options := Options{Meter: meter.DefaultMeter}
for _, o := range opts {
o(&options)
}
@ -86,48 +56,12 @@ func NewHandler(opts ...Option) *Handler {
}
func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.Frame) error {
log, ok := logger.FromContext(ctx)
if !ok {
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
buf := bytes.NewBuffer(nil)
if err := h.opts.Meter.Write(buf, h.opts.MeterOptions...); err != nil {
return errors.InternalServerError(h.opts.Name, "%v", err)
}
rsp.Data = buf.Bytes()
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
}

View File

@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
// versions:
// - protoc-gen-go-micro v4.0.2
// - protoc v4.23.4
// - protoc-gen-go-micro v4.0.0
// - protoc v3.21.12
// source: meter/meter.proto
package meter
@ -9,11 +9,23 @@ package meter
import (
context "context"
codec "go.unistack.org/micro-proto/v4/codec"
v4 "go.unistack.org/micro-server-http/v4"
)
var (
MeterServiceName = "MeterService"
)
var (
MeterServiceServerEndpoints = []v4.EndpointMetadata{
{
Name: "MeterService.Metrics",
Path: "/metrics",
Method: "GET",
Body: "",
Stream: false,
},
}
)
type MeterServiceServer interface {
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error

View File

@ -1,5 +1,5 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v4.0.2
// protoc-gen-go-micro version: v4.0.0
// source: meter/meter.proto
package meter
@ -8,22 +8,9 @@ import (
context "context"
codec "go.unistack.org/micro-proto/v4/codec"
v4 "go.unistack.org/micro-server-http/v4"
options "go.unistack.org/micro/v4/options"
server "go.unistack.org/micro/v4/server"
)
var (
MeterServiceServerEndpoints = []v4.EndpointMetadata{
{
Name: "MeterService.Metrics",
Path: "/metrics",
Method: "GET",
Body: "",
Stream: false,
},
}
)
type meterServiceServer struct {
MeterServiceServer
}
@ -32,7 +19,7 @@ func (h *meterServiceServer) Metrics(ctx context.Context, req *codec.Frame, rsp
return h.MeterServiceServer.Metrics(ctx, req, rsp)
}
func RegisterMeterServiceServer(s server.Server, sh MeterServiceServer, opts ...options.Option) error {
func RegisterMeterServiceServer(s server.Server, sh MeterServiceServer, opts ...server.HandlerOption) error {
type meterService interface {
Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error
}
@ -40,7 +27,7 @@ func RegisterMeterServiceServer(s server.Server, sh MeterServiceServer, opts ...
meterService
}
h := &meterServiceServer{sh}
var nopts []options.Option
var nopts []server.HandlerOption
nopts = append(nopts, v4.HandlerEndpoints(MeterServiceServerEndpoints))
return s.Handle(&MeterService{h}, append(nopts, opts...)...)
return s.Handle(s.NewHandler(&MeterService{h}, append(nopts, opts...)...))
}

View File

@ -1,49 +0,0 @@
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)
})
}
}

View File

@ -1,19 +0,0 @@
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)
}
}

View File

@ -0,0 +1,20 @@
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>
};

View File

@ -1,18 +1,24 @@
package swagger
package swagger // import "go.unistack.org/micro-server-http/v4/handler/swagger"
import (
"context"
"io/fs"
"net/http"
yamlcodec "go.unistack.org/micro-codec-yaml/v4"
rutil "go.unistack.org/micro/v4/util/reflect"
httpsrv "go.unistack.org/micro-server-http/v4"
"go.unistack.org/micro/v4/server"
)
type (
Hook func([]byte) []byte
ErrorHandler func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int)
)
// 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()
var Handler = func(fsys fs.FS, hooks []Hook, h httpsrv.ErrorHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
h(r.Context())
w.WriteHeader(http.StatusNotFound)
return
}
@ -29,32 +35,6 @@ var Handler = func(dst map[string]interface{}, fsys fs.FS) http.HandlerFunc {
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
View File

@ -15,7 +15,6 @@ import (
"go.unistack.org/micro/v4/codec"
"go.unistack.org/micro/v4/logger"
"go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v4/register"
"go.unistack.org/micro/v4/server"
rhttp "go.unistack.org/micro/v4/util/http"
@ -25,11 +24,11 @@ import (
var _ server.Server = (*Server)(nil)
type Server struct {
hd interface{}
hd server.Handler
rsvc *register.Service
handlers map[string]interface{}
handlers map[string]server.Handler
exit chan chan error
errorHandler func(context.Context, interface{}, http.ResponseWriter, *http.Request, error, int)
errorHandler func(context.Context, server.Handler, http.ResponseWriter, *http.Request, error, int)
pathHandlers *rhttp.Trie
opts server.Options
registerRPC bool
@ -58,7 +57,7 @@ func (h *Server) Options() server.Options {
return opts
}
func (h *Server) Init(opts ...options.Option) error {
func (h *Server) Init(opts ...server.Option) error {
if len(opts) == 0 && h.init {
return nil
}
@ -68,11 +67,11 @@ func (h *Server) Init(opts ...options.Option) error {
for _, o := range opts {
o(&h.opts)
}
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 {
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 {
h.errorHandler = fn
}
if h.handlers == nil {
h.handlers = make(map[string]interface{})
h.handlers = make(map[string]server.Handler)
}
if h.pathHandlers == nil {
h.pathHandlers = rhttp.NewTrie()
@ -111,6 +110,10 @@ func (h *Server) Init(opts ...options.Option) error {
h.RUnlock()
return err
}
if err := h.opts.Transport.Init(); err != nil {
h.RUnlock()
return err
}
h.RUnlock()
h.Lock()
@ -120,24 +123,12 @@ func (h *Server) Init(opts ...options.Option) error {
return nil
}
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
}
func (h *Server) Handle(handler server.Handler) error {
// passed unknown handler
hdlr, ok := handler.(*httpHandler)
if !ok {
h.Lock()
if h.handlers == nil {
h.handlers = make(map[string]interface{})
}
for _, v := range endpointMetadata {
h.handlers[v.Name] = h.newHTTPHandler(handler, opts...)
}
h.hd = handler
h.Unlock()
return nil
}
@ -150,11 +141,19 @@ func (h *Server) Handle(handler interface{}, opts ...options.Option) error {
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
}
func (h *Server) newHTTPHandler(handler interface{}, opts ...options.Option) *httpHandler {
options := server.NewHandleOptions(opts...)
func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) server.Handler {
options := server.NewHandlerOptions(opts...)
eps := make([]*register.Endpoint, 0, len(options.Metadata))
for name, metadata := range options.Metadata {
@ -198,16 +197,16 @@ func (h *Server) newHTTPHandler(handler interface{}, opts ...options.Option) *ht
}
if method.Name == "" && h.opts.Logger.V(logger.ErrorLevel) {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil method for %s", mname))
h.opts.Logger.Errorf(h.opts.Context, "nil method for %s", mname)
continue
}
mtype, err := prepareEndpoint(method)
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("%v", err))
h.opts.Logger.Errorf(h.opts.Context, "%v", err)
continue
} else if mtype == nil {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil mtype for %s", mname))
h.opts.Logger.Errorf(h.opts.Context, "nil mtype for %s", mname)
continue
}
@ -218,13 +217,13 @@ func (h *Server) newHTTPHandler(handler interface{}, opts ...options.Option) *ht
hdlr.name = name
if err := hdlr.handlers.Insert([]string{md["Method"]}, md["Path"], pth); err != nil {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add handler for %s %s", md["Method"][0], md["Path"][0]))
h.opts.Logger.Errorf(h.opts.Context, "cant add handler for %s %s", md["Method"], md["Path"])
}
if h.registerRPC {
h.opts.Logger.Info(h.opts.Context, fmt.Sprintf("register rpc handler for http.MethodPost %s /%s", hn, hn))
h.opts.Logger.Infof(h.opts.Context, "register rpc handler for http.MethodPost %s /%s", hn, hn)
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add rpc handler for http.MethodPost %s /%s", hn, hn))
h.opts.Logger.Errorf(h.opts.Context, "cant add rpc handler for http.MethodPost %s /%s", hn, hn)
}
}
}
@ -248,16 +247,16 @@ func (h *Server) newHTTPHandler(handler interface{}, opts ...options.Option) *ht
}
if method.Name == "" && h.opts.Logger.V(logger.ErrorLevel) {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil method for %s", mname))
h.opts.Logger.Errorf(h.opts.Context, "nil method for %s", mname)
continue
}
mtype, err := prepareEndpoint(method)
if err != nil && h.opts.Logger.V(logger.ErrorLevel) {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("%v", err))
h.opts.Logger.Errorf(h.opts.Context, "%v", err)
continue
} else if mtype == nil {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("nil mtype for %s", mname))
h.opts.Logger.Errorf(h.opts.Context, "nil mtype for %s", mname)
continue
}
@ -268,13 +267,13 @@ func (h *Server) newHTTPHandler(handler interface{}, opts ...options.Option) *ht
hdlr.name = name
if err := hdlr.handlers.Insert([]string{md.Method}, md.Path, pth); err != nil {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add handler for %s %s", md.Method, md.Path))
h.opts.Logger.Errorf(h.opts.Context, "cant add handler for %s %s", md.Method, md.Path)
}
if h.registerRPC {
h.opts.Logger.Info(h.opts.Context, fmt.Sprintf("register rpc handler for http.MethodPost %s /%s", hn, hn))
h.opts.Logger.Infof(h.opts.Context, "register rpc handler for http.MethodPost %s /%s", hn, hn)
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {
h.opts.Logger.Error(h.opts.Context, fmt.Sprintf("cant add rpc handler for http.MethodPost %s /%s", hn, hn))
h.opts.Logger.Errorf(h.opts.Context, "cant add rpc handler for http.MethodPost %s /%s", hn, hn)
}
}
}
@ -286,11 +285,7 @@ func (h *Server) Register() error {
var eps []*register.Endpoint
h.RLock()
for _, hdlr := range h.handlers {
hd, ok := hdlr.(*httpHandler)
if !ok {
continue
}
eps = append(eps, hd.Endpoints()...)
eps = append(eps, hdlr.Endpoints()...)
}
rsvc := h.rsvc
config := h.opts
@ -308,7 +303,7 @@ func (h *Server) Register() error {
if err != nil {
return err
}
service.Nodes[0].Metadata.Set("protocol", "http")
service.Nodes[0].Metadata["protocol"] = "http"
service.Endpoints = eps
h.RLock()
@ -317,7 +312,7 @@ func (h *Server) Register() error {
if !registered {
if config.Logger.V(logger.InfoLevel) {
config.Logger.Info(config.Context, fmt.Sprintf("Register [%s] Registering node: %s", config.Register.String(), service.Nodes[0].ID))
config.Logger.Infof(config.Context, "Register [%s] Registering node: %s", config.Register.String(), service.Nodes[0].ID)
}
}
@ -350,7 +345,7 @@ func (h *Server) Deregister() error {
}
if config.Logger.V(logger.InfoLevel) {
config.Logger.Info(config.Context, fmt.Sprintf("Deregistering node: %s", service.Nodes[0].ID))
config.Logger.Infof(config.Context, "Deregistering node: %s", service.Nodes[0].ID)
}
if err := server.DefaultDeregisterFunc(service, config); err != nil {
@ -400,7 +395,7 @@ func (h *Server) Start() error {
}
if config.Logger.V(logger.InfoLevel) {
config.Logger.Info(config.Context, fmt.Sprintf("Listening on %s", ts.Addr().String()))
config.Logger.Infof(config.Context, "Listening on %s", ts.Addr().String())
}
h.Lock()
@ -408,12 +403,13 @@ func (h *Server) Start() error {
h.Unlock()
var handler http.Handler
var srvFunc func(net.Listener) error
// nolint: nestif
if h.opts.Context != nil {
if hs, ok := h.opts.Context.Value(serverKey{}).(*http.Server); ok && hs != nil {
if hs.Handler == nil && h.hd != nil {
if hdlr, ok := h.hd.(http.Handler); ok {
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
hs.Handler = hdlr
handler = hs.Handler
}
@ -429,7 +425,7 @@ func (h *Server) Start() error {
case len(h.handlers) > 0 && h.hd != nil:
handler = h
case handler == nil && h.hd != nil:
if hdlr, ok := h.hd.(http.Handler); ok {
if hdlr, ok := h.hd.Handler().(http.Handler); ok {
handler = hdlr
}
}
@ -440,7 +436,7 @@ func (h *Server) Start() error {
if err := config.RegisterCheck(h.opts.Context); err != nil {
if config.Logger.V(logger.ErrorLevel) {
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register check error: %s", config.Name, config.ID, err))
config.Logger.Errorf(config.Context, "Server %s-%s register check error: %s", config.Name, config.ID, err)
}
} else {
if err = h.Register(); err != nil {
@ -450,7 +446,6 @@ func (h *Server) Start() error {
fn := handler
var hs *http.Server
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
@ -458,19 +453,25 @@ func (h *Server) Start() error {
fn = mwf[i-1](fn)
}
}
var ok bool
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 {
hs.Handler = fn
} else {
hs = &http.Server{Handler: fn}
srvFunc = hs.Serve
}
}
if srvFunc != nil {
go func() {
if cerr := hs.Serve(ts); cerr != nil && !errors.Is(cerr, net.ErrClosed) {
h.opts.Logger.Error(h.opts.Context, cerr.Error())
if cerr := srvFunc(ts); cerr != nil && !errors.Is(cerr, net.ErrClosed) {
h.opts.Logger.Error(h.opts.Context, cerr)
}
}()
} 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() {
t := new(time.Ticker)
@ -496,28 +497,28 @@ func (h *Server) Start() error {
// nolint: nestif
if rerr != nil && registered {
if config.Logger.V(logger.ErrorLevel) {
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register check error: %s, deregister it", config.Name, config.ID, rerr))
config.Logger.Errorf(config.Context, "Server %s-%s register check error: %s, deregister it", config.Name, config.ID, rerr)
}
// deregister self in case of error
if err := h.Deregister(); err != nil {
if config.Logger.V(logger.ErrorLevel) {
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s deregister error: %s", config.Name, config.ID, err))
config.Logger.Errorf(config.Context, "Server %s-%s deregister error: %s", config.Name, config.ID, err)
}
}
} else if rerr != nil && !registered {
if config.Logger.V(logger.ErrorLevel) {
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register check error: %s", config.Name, config.ID, rerr))
config.Logger.Errorf(config.Context, "Server %s-%s register check error: %s", config.Name, config.ID, rerr)
}
continue
}
if err := h.Register(); err != nil {
if config.Logger.V(logger.ErrorLevel) {
config.Logger.Error(config.Context, fmt.Sprintf("Server %s-%s register error: %s", config.Name, config.ID, err))
config.Logger.Errorf(config.Context, "Server %s-%s register error: %s", config.Name, config.ID, err)
}
}
if err := h.Register(); err != nil {
config.Logger.Error(config.Context, fmt.Sprintf("Server register error: %s", err))
config.Logger.Errorf(config.Context, "Server register error: %s", err)
}
// wait for exit
case ch = <-h.exit:
@ -527,18 +528,10 @@ func (h *Server) Start() error {
// deregister
if err := h.Deregister(); err != nil {
config.Logger.Error(config.Context, fmt.Sprintf("Server deregister error: %s", err))
config.Logger.Errorf(config.Context, "Server deregister error: %s", err)
}
ctx, cancel := context.WithTimeout(context.Background(), h.opts.GracefulTimeout)
defer cancel()
err := hs.Shutdown(ctx)
if err != nil {
err = hs.Close()
}
ch <- err
ch <- ts.Close()
}()
return nil
@ -558,7 +551,7 @@ func (h *Server) Name() string {
return h.opts.Name
}
func NewServer(opts ...options.Option) *Server {
func NewServer(opts ...server.Option) *Server {
options := server.NewOptions(opts...)
eh := DefaultErrorHandler
if v, ok := options.Context.Value(errorHandlerKey{}).(errorHandler); ok && v != nil {

View File

@ -5,7 +5,7 @@ import (
"fmt"
"net/http"
"go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v4/server"
)
// SetError pass error to caller
@ -79,24 +79,24 @@ func GetRspCode(ctx context.Context) int {
type middlewareKey struct{}
// Middleware passes http middlewares
func Middleware(mw ...func(http.Handler) http.Handler) options.Option {
return options.ContextOption(middlewareKey{}, mw)
func Middleware(mw ...func(http.Handler) http.Handler) server.Option {
return server.SetOption(middlewareKey{}, mw)
}
type serverKey struct{}
// HTTPServer provide ability to pass *http.Server
func HTTPServer(hs *http.Server) options.Option {
return options.ContextOption(serverKey{}, hs)
func HTTPServer(hs *http.Server) server.Option {
return server.SetOption(serverKey{}, hs)
}
type errorHandler func(ctx context.Context, s interface{}, w http.ResponseWriter, r *http.Request, err error, status int)
type errorHandler func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int)
type errorHandlerKey struct{}
// ErrorHandler specifies handler for errors
func ErrorHandler(fn errorHandler) options.Option {
return options.ContextOption(errorHandlerKey{}, fn)
func ErrorHandler(fn errorHandler) server.Option {
return server.SetOption(errorHandlerKey{}, fn)
}
type (
@ -107,18 +107,12 @@ type (
)
// PathHandler specifies http handler for path regexp
func PathHandler(method, path string, handler http.HandlerFunc) options.Option {
return func(src interface{}) error {
vctx, err := options.Get(src, ".Context")
if err != nil {
return err
func PathHandler(method, path string, handler http.HandlerFunc) server.Option {
return func(o *server.Options) {
if o.Context == nil {
o.Context = context.Background()
}
ctx, ok := vctx.(context.Context)
if !ok {
return fmt.Errorf("invalid option")
}
v, ok := ctx.Value(pathHandlerKey{}).(*pathHandlerVal)
v, ok := o.Context.Value(pathHandlerKey{}).(*pathHandlerVal)
if !ok {
v = &pathHandlerVal{h: make(map[string]map[string]http.HandlerFunc)}
}
@ -127,17 +121,16 @@ func PathHandler(method, path string, handler http.HandlerFunc) options.Option {
m = make(map[string]http.HandlerFunc)
v.h[method] = m
}
ctx = context.WithValue(ctx, pathHandlerKey{}, v)
m[path] = handler
return options.Set(src, ctx, ".Context")
o.Context = context.WithValue(o.Context, pathHandlerKey{}, v)
}
}
type registerRPCHandlerKey struct{}
// RegisterRPCHandler registers compatibility endpoints with /ServiceName.ServiceEndpoint method POST
func RegisterRPCHandler(b bool) options.Option {
return options.ContextOption(registerRPCHandlerKey{}, b)
func RegisterRPCHandler(b bool) server.Option {
return server.SetOption(registerRPCHandlerKey{}, b)
}
type handlerEndpointsKey struct{}
@ -150,8 +143,8 @@ type EndpointMetadata struct {
Stream bool
}
func HandlerEndpoints(md []EndpointMetadata) options.Option {
return options.ContextOption(handlerEndpointsKey{}, md)
func HandlerEndpoints(md []EndpointMetadata) server.HandlerOption {
return server.SetHandlerOption(handlerEndpointsKey{}, md)
}
type handlerOptions struct {

View File

@ -1,8 +0,0 @@
//go:build tools
package http
import (
_ "go.unistack.org/micro-proto/v4"
_ "go.unistack.org/protoc-gen-go-micro/v4"
)

View File

@ -31,13 +31,15 @@ func FillRequest(ctx context.Context, req interface{}, opts ...FillRequestOption
}
}
cookies := md["Cookie"]
cookies := strings.Split(md["Cookie"], ";")
cmd := make(map[string]string, len(cookies))
kv := strings.Split(cookies, "=")
for _, cookie := range cookies {
kv := strings.Split(cookie, "=")
if len(kv) != 2 {
return nil
continue
}
cmd[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
}
for idx := 0; idx < len(options.cookies)/2; idx += 2 {
k := http.CanonicalHeaderKey(options.cookies[idx])
v, ok := cmd[k]