Compare commits
9 Commits
Author | SHA1 | Date | |
---|---|---|---|
b5d9fd5764 | |||
|
39ad61b34e | ||
1cb2b3c241 | |||
732b5685fb | |||
6cddb5f218 | |||
dd4578a57d | |||
c6b72d7a7a | |||
545e372b82 | |||
d7ffae7b16 |
2
.github/workflows/job_coverage.yml
vendored
2
.github/workflows/job_coverage.yml
vendored
@@ -8,8 +8,6 @@ on:
|
||||
- '.gitea/**'
|
||||
pull_request:
|
||||
branches: [ main, v3, v4 ]
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
||||
|
53
.github/workflows/job_sync.yml
vendored
53
.github/workflows/job_sync.yml
vendored
@@ -3,11 +3,6 @@ name: sync
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/5 * * * *'
|
||||
# push:
|
||||
# branches: [ master, v3, v4 ]
|
||||
# paths-ignore:
|
||||
# - '.github/**'
|
||||
# - '.gitea/**'
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -23,35 +18,77 @@ jobs:
|
||||
echo "machine git.unistack.org login vtolstov password ${{ secrets.TOKEN_GITEA }}" >> /root/.netrc
|
||||
echo "machine github.com login vtolstov password ${{ secrets.TOKEN_GITHUB }}" >> /root/.netrc
|
||||
|
||||
- name: check master
|
||||
id: check_master
|
||||
run: |
|
||||
src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
|
||||
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
|
||||
echo "src_hash=$src_hash"
|
||||
echo "dst_hash=$dst_hash"
|
||||
if [ "$src_hash" != "$dst_hash" ]; then
|
||||
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: sync master
|
||||
if: steps.check_master.outputs.sync_needed == 'true'
|
||||
run: |
|
||||
git clone --filter=blob:none --filter=tree:0 --branch master --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
|
||||
cd repo
|
||||
git remote add --no-tags --track master upstream https://github.com/${GITHUB_REPOSITORY}
|
||||
git remote add --no-tags --fetch --track master upstream https://github.com/${GITHUB_REPOSITORY}
|
||||
git pull --rebase upstream master
|
||||
git push upstream master --progress
|
||||
git push origin master --progress
|
||||
cd ../
|
||||
rm -rf repo
|
||||
|
||||
- name: check v3
|
||||
id: check_v3
|
||||
run: |
|
||||
src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/v3 | cut -f1)
|
||||
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/v3 | cut -f1)
|
||||
echo "src_hash=$src_hash"
|
||||
echo "dst_hash=$dst_hash"
|
||||
if [ "$src_hash" != "$dst_hash" ]; then
|
||||
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: sync v3
|
||||
if: steps.check_v3.outputs.sync_needed == 'true'
|
||||
run: |
|
||||
git clone --filter=blob:none --filter=tree:0 --branch v3 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
|
||||
cd repo
|
||||
git remote add --no-tags --fetch --track v3 upstream https://github.com/${GITHUB_REPOSITORY}
|
||||
git pull --rebase upstream v3
|
||||
git push upstream v3
|
||||
git push upstream v3 --progress
|
||||
git push origin v3 --progress
|
||||
cd ../
|
||||
rm -rf repo
|
||||
|
||||
- name: check v4
|
||||
id: check_v4
|
||||
run: |
|
||||
src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/v4 | cut -f1)
|
||||
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/v4 | cut -f1)
|
||||
echo "src_hash=$src_hash"
|
||||
echo "dst_hash=$dst_hash"
|
||||
if [ "$src_hash" != "$dst_hash" ]; then
|
||||
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: sync v4
|
||||
if: steps.check_v4.outputs.sync_needed == 'true'
|
||||
run: |
|
||||
git clone --filter=blob:none --filter=tree:0 --branch v4 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
|
||||
cd repo
|
||||
git remote add --no-tags --fetch --track v4 upstream https://github.com/${GITHUB_REPOSITORY}
|
||||
git pull --rebase upstream v4
|
||||
git push upstream v4
|
||||
git push upstream v4 --progress
|
||||
git push origin v4 --progress
|
||||
cd ../
|
||||
rm -rf repo
|
||||
|
@@ -1,5 +1,5 @@
|
||||
# HTTP Server
|
||||

|
||||

|
||||
|
||||
The HTTP Server is a go-micro.Server. It's a partial implementation which strips out codecs, transports, etc but enables you
|
||||
to create a HTTP Server that could potentially be used for REST based API services.
|
||||
|
5
go.mod
5
go.mod
@@ -1,8 +1,9 @@
|
||||
module go.unistack.org/micro-server-http/v4
|
||||
|
||||
go 1.23.0
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/stretchr/testify v1.10.0
|
||||
go.unistack.org/micro-client-http/v4 v4.1.0
|
||||
go.unistack.org/micro-codec-yaml/v4 v4.1.0
|
||||
go.unistack.org/micro-proto/v4 v4.1.0
|
||||
@@ -12,10 +13,12 @@ require (
|
||||
|
||||
require (
|
||||
github.com/ash3in/uuidv8 v1.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/google/gnostic v0.7.0 // indirect
|
||||
github.com/google/gnostic-models v0.6.9 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/matoous/go-nanoid v1.5.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/spf13/cast v1.7.1 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250428153025-10db94c68c34 // indirect
|
||||
|
81
handler.go
81
handler.go
@@ -9,7 +9,6 @@ import (
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.unistack.org/micro/v4/errors"
|
||||
@@ -46,7 +45,6 @@ type httpHandler struct {
|
||||
handlers *rhttp.Trie
|
||||
name string
|
||||
sopts server.Options
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (h *httpHandler) Name() string {
|
||||
@@ -103,8 +101,9 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
||||
ct = htype
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), rspCodeKey{}, &rspCodeVal{})
|
||||
ctx = context.WithValue(ctx, rspHeaderKey{}, &rspHeaderVal{})
|
||||
ctx := context.WithValue(r.Context(), rspStatusCodeKey{}, &rspStatusCodeVal{})
|
||||
ctx = context.WithValue(ctx, rspMetadataKey{}, &rspMetadataVal{m: metadata.New(0)})
|
||||
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(len(r.Header) + 8)
|
||||
@@ -128,6 +127,7 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
||||
}
|
||||
|
||||
ctx = metadata.NewIncomingContext(ctx, md)
|
||||
ctx = metadata.NewOutgoingContext(ctx, metadata.New(0))
|
||||
|
||||
path := r.URL.Path
|
||||
|
||||
@@ -257,17 +257,6 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
||||
err = rerr.(error)
|
||||
}
|
||||
|
||||
md, ok := metadata.FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(0)
|
||||
}
|
||||
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
|
||||
for k, v := range nmd {
|
||||
md[k] = append(md[k], v...)
|
||||
}
|
||||
}
|
||||
ctx = metadata.NewOutgoingContext(ctx, md)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -291,19 +280,8 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
||||
appErr := fn(ctx, hr, replyv.Interface())
|
||||
|
||||
w.Header().Set(metadata.HeaderContentType, ct)
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
for k, v := range md {
|
||||
for i := range v {
|
||||
w.Header().Set(k, v[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if md := getRspHeader(ctx); md != nil {
|
||||
for k, v := range md {
|
||||
for _, vv := range v {
|
||||
w.Header().Add(k, vv)
|
||||
}
|
||||
}
|
||||
for k, v := range getResponseMetadata(ctx) {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
|
||||
if cf, err = h.newCodec(nct); err != nil {
|
||||
@@ -332,7 +310,7 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
|
||||
return
|
||||
}
|
||||
|
||||
if nscode := GetRspCode(ctx); nscode != 0 {
|
||||
if nscode := GetResponseStatusCode(ctx); nscode != 0 {
|
||||
scode = nscode
|
||||
}
|
||||
w.WriteHeader(scode)
|
||||
@@ -351,8 +329,8 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
ts := time.Now()
|
||||
|
||||
ctx := context.WithValue(r.Context(), rspCodeKey{}, &rspCodeVal{})
|
||||
ctx = context.WithValue(ctx, rspHeaderKey{}, &rspHeaderVal{})
|
||||
ctx := context.WithValue(r.Context(), rspStatusCodeKey{}, &rspStatusCodeVal{})
|
||||
ctx = context.WithValue(ctx, rspMetadataKey{}, &rspMetadataVal{m: metadata.New(0)})
|
||||
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
@@ -373,10 +351,11 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
md["Proto"] = append(md["Proto"], r.Proto)
|
||||
md["Content-Length"] = append(md["Content-Length"], fmt.Sprintf("%d", r.ContentLength))
|
||||
if len(r.TransferEncoding) > 0 {
|
||||
md["TransferEncoding"] = append(md["Content-Length"], r.TransferEncoding...)
|
||||
md["Transfer-Encoding"] = append(md["Transfer-Encoding"], r.TransferEncoding...)
|
||||
}
|
||||
md["Host"] = append(md["Host"], r.Host)
|
||||
md["RequestURI"] = append(md["RequestURI"], r.RequestURI)
|
||||
|
||||
ctx = metadata.NewIncomingContext(ctx, md)
|
||||
ctx = metadata.NewOutgoingContext(ctx, metadata.New(0))
|
||||
|
||||
@@ -442,7 +421,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
),
|
||||
)
|
||||
defer func() {
|
||||
n := GetRspCode(ctx)
|
||||
n := GetResponseStatusCode(ctx)
|
||||
if s, _ := sp.Status(); s != tracer.SpanStatusError && n > 399 {
|
||||
sp.SetStatus(tracer.SpanStatusError, http.StatusText(n))
|
||||
}
|
||||
@@ -454,7 +433,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
h.opts.Meter.Counter(semconv.ServerRequestInflight, "endpoint", endpointName, "server", "http").Inc()
|
||||
|
||||
defer func() {
|
||||
n := GetRspCode(ctx)
|
||||
n := GetResponseStatusCode(ctx)
|
||||
if n > 399 {
|
||||
h.opts.Meter.Counter(semconv.ServerRequestTotal, "endpoint", endpointName, "server", "http", "status", "success", "code", strconv.Itoa(n)).Inc()
|
||||
} else {
|
||||
@@ -482,7 +461,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
)
|
||||
|
||||
defer func() {
|
||||
if n := GetRspCode(ctx); n > 399 {
|
||||
if n := GetResponseStatusCode(ctx); n > 399 {
|
||||
sp.SetStatus(tracer.SpanStatusError, http.StatusText(n))
|
||||
} else {
|
||||
sp.SetStatus(tracer.SpanStatusError, http.StatusText(http.StatusNotFound))
|
||||
@@ -521,7 +500,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
h.opts.Meter.Histogram(semconv.ServerRequestDurationSeconds, "endpoint", handler.name, "server", "http").Update(te.Seconds())
|
||||
h.opts.Meter.Counter(semconv.ServerRequestInflight, "endpoint", handler.name, "server", "http").Dec()
|
||||
|
||||
n := GetRspCode(ctx)
|
||||
n := GetResponseStatusCode(ctx)
|
||||
if n > 399 {
|
||||
h.opts.Meter.Counter(semconv.ServerRequestTotal, "endpoint", handler.name, "server", "http", "status", "failure", "code", strconv.Itoa(n)).Inc()
|
||||
} else {
|
||||
@@ -531,7 +510,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
defer func() {
|
||||
n := GetRspCode(ctx)
|
||||
n := GetResponseStatusCode(ctx)
|
||||
if n > 399 {
|
||||
if s, _ := sp.Status(); s != tracer.SpanStatusError {
|
||||
sp.SetStatus(tracer.SpanStatusError, http.StatusText(n))
|
||||
@@ -625,17 +604,6 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
err = rerr.(error)
|
||||
}
|
||||
|
||||
md, ok := metadata.FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(0)
|
||||
}
|
||||
if nmd, ok := metadata.FromOutgoingContext(fctx); ok {
|
||||
for k, v := range nmd {
|
||||
md[k] = append(md[k], v...)
|
||||
}
|
||||
}
|
||||
ctx = metadata.NewOutgoingContext(ctx, md)
|
||||
|
||||
if err != nil && sp != nil {
|
||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||
}
|
||||
@@ -662,19 +630,8 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
appErr := fn(ctx, hr, replyv.Interface())
|
||||
|
||||
w.Header().Set(metadata.HeaderContentType, ct)
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); ok {
|
||||
for k, v := range md {
|
||||
for i := range v {
|
||||
w.Header().Set(k, v[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if md := getRspHeader(ctx); md != nil {
|
||||
for k, v := range md {
|
||||
for _, vv := range v {
|
||||
w.Header().Add(k, vv)
|
||||
}
|
||||
}
|
||||
for k, v := range getResponseMetadata(ctx) {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
|
||||
if cf, err = h.newCodec(nct); err != nil {
|
||||
@@ -703,7 +660,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
handler.sopts.Logger.Error(handler.sopts.Context, "handler error", err)
|
||||
}
|
||||
scode = http.StatusInternalServerError
|
||||
} else if nscode := GetRspCode(ctx); nscode != 0 {
|
||||
} else if nscode := GetResponseStatusCode(ctx); nscode != 0 {
|
||||
scode = nscode
|
||||
}
|
||||
|
||||
|
@@ -4,11 +4,12 @@ import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"io"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
codecpb "go.unistack.org/micro-proto/v4/codec"
|
||||
httpsrv "go.unistack.org/micro-server-http/v4"
|
||||
"go.unistack.org/micro/v4/logger"
|
||||
"go.unistack.org/micro/v4/metadata"
|
||||
"go.unistack.org/micro/v4/meter"
|
||||
@@ -90,28 +91,52 @@ func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.
|
||||
log = logger.DefaultLogger
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
if md, ok := metadata.FromIncomingContext(ctx); ok && gzipAccepted(md) && !h.Options.DisableCompress {
|
||||
err = h.writeMetricsGzip(ctx, rsp)
|
||||
} else {
|
||||
err = h.writeMetricsPlain(ctx, rsp)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Error(ctx, "http/meter write failed", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) writeMetricsGzip(ctx context.Context, rsp *codecpb.Frame) error {
|
||||
httpsrv.AppendResponseMetadata(ctx, metadata.Pairs(contentEncodingHeader, "gzip"))
|
||||
|
||||
buf := bufPool.Get().(*bytes.Buffer)
|
||||
defer bufPool.Put(buf)
|
||||
buf.Reset()
|
||||
|
||||
w := io.Writer(buf)
|
||||
gz := gzipPool.Get().(*gzip.Writer)
|
||||
defer gzipPool.Put(gz)
|
||||
gz.Reset(buf)
|
||||
|
||||
if md, ok := metadata.FromOutgoingContext(ctx); gzipAccepted(md) && ok && !h.Options.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.Options.Meter.Write(gz, h.Options.MeterOptions...); err != nil {
|
||||
return fmt.Errorf("meter write: %w", err)
|
||||
}
|
||||
|
||||
if err := h.Options.Meter.Write(w, h.Options.MeterOptions...); err != nil {
|
||||
log.Error(ctx, "http/meter write failed", err)
|
||||
return nil
|
||||
if err := gz.Close(); err != nil {
|
||||
return fmt.Errorf("gzip close: %w", err)
|
||||
}
|
||||
|
||||
rsp.Data = buf.Bytes()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) writeMetricsPlain(_ context.Context, rsp *codecpb.Frame) error {
|
||||
buf := bufPool.Get().(*bytes.Buffer)
|
||||
defer bufPool.Put(buf)
|
||||
buf.Reset()
|
||||
|
||||
if err := h.Options.Meter.Write(buf, h.Options.MeterOptions...); err != nil {
|
||||
return fmt.Errorf("meter write: %w", err)
|
||||
}
|
||||
|
||||
rsp.Data = buf.Bytes()
|
||||
|
@@ -1,11 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHandler(t *testing.T) {
|
||||
ctx := context.WithValue(context.TODO(), rspCodeKey{}, &rspCodeVal{})
|
||||
SetRspCode(ctx, 404)
|
||||
}
|
84
http.go
84
http.go
@@ -36,18 +36,18 @@ type Server struct {
|
||||
stateReady *atomic.Uint32
|
||||
stateHealth *atomic.Uint32
|
||||
registerRPC bool
|
||||
sync.RWMutex
|
||||
registered bool
|
||||
init bool
|
||||
mu sync.RWMutex
|
||||
registered bool
|
||||
init bool
|
||||
}
|
||||
|
||||
func (h *Server) newCodec(ct string) (codec.Codec, error) {
|
||||
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
|
||||
ct = ct[:idx]
|
||||
}
|
||||
h.RLock()
|
||||
h.mu.RLock()
|
||||
cf, ok := h.opts.Codecs[ct]
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
if ok {
|
||||
return cf, nil
|
||||
}
|
||||
@@ -55,9 +55,9 @@ func (h *Server) newCodec(ct string) (codec.Codec, error) {
|
||||
}
|
||||
|
||||
func (h *Server) Options() server.Options {
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
opts := h.opts
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
return opts
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func (h *Server) Init(opts ...server.Option) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
|
||||
for _, o := range opts {
|
||||
o(&h.opts)
|
||||
@@ -89,41 +89,41 @@ func (h *Server) Init(opts ...server.Option) error {
|
||||
for pm, ps := range phs.h {
|
||||
for pp, ph := range ps {
|
||||
if err := h.pathHandlers.Insert([]string{pm}, pp, ph); err != nil {
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
|
||||
h.RLock()
|
||||
h.mu.RLock()
|
||||
if err := h.opts.Register.Init(); err != nil {
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Broker.Init(); err != nil {
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Tracer.Init(); err != nil {
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Logger.Init(); err != nil {
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
return err
|
||||
}
|
||||
if err := h.opts.Meter.Init(); err != nil {
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
return err
|
||||
}
|
||||
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
h.init = true
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -132,27 +132,27 @@ func (h *Server) Handle(handler server.Handler) error {
|
||||
// passed unknown handler
|
||||
hdlr, ok := handler.(*httpHandler)
|
||||
if !ok {
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
h.hd = handler
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// passed http.Handler like some muxer
|
||||
if _, ok := hdlr.hd.(http.Handler); ok {
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
h.hd = handler
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// passed micro compat handler
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
if h.handlers == nil {
|
||||
h.handlers = make(map[string]server.Handler)
|
||||
}
|
||||
h.handlers[handler.Name()] = handler
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -294,10 +294,10 @@ func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) s
|
||||
}
|
||||
|
||||
func (h *Server) Register() error {
|
||||
h.RLock()
|
||||
h.mu.RLock()
|
||||
rsvc := h.rsvc
|
||||
config := h.opts
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
|
||||
// if service already filled, reuse it and return early
|
||||
if rsvc != nil {
|
||||
@@ -312,9 +312,9 @@ func (h *Server) Register() error {
|
||||
return err
|
||||
}
|
||||
|
||||
h.RLock()
|
||||
h.mu.RLock()
|
||||
registered := h.registered
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
|
||||
if !registered {
|
||||
if config.Logger.V(logger.InfoLevel) {
|
||||
@@ -332,19 +332,19 @@ func (h *Server) Register() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
|
||||
h.registered = true
|
||||
h.rsvc = service
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Server) Deregister() error {
|
||||
h.RLock()
|
||||
h.mu.RLock()
|
||||
config := h.opts
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
|
||||
service, err := server.NewRegisterService(h)
|
||||
if err != nil {
|
||||
@@ -359,24 +359,24 @@ func (h *Server) Deregister() error {
|
||||
return err
|
||||
}
|
||||
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
h.rsvc = nil
|
||||
|
||||
if !h.registered {
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
h.registered = false
|
||||
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Server) Start() error {
|
||||
h.RLock()
|
||||
h.mu.RLock()
|
||||
config := h.opts
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
|
||||
// micro: config.Transport.Listen(config.Address)
|
||||
var ts net.Listener
|
||||
@@ -406,9 +406,9 @@ func (h *Server) Start() error {
|
||||
config.Logger.Info(config.Context, "Listening on "+ts.Addr().String())
|
||||
}
|
||||
|
||||
h.Lock()
|
||||
h.mu.Lock()
|
||||
h.opts.Address = ts.Addr().String()
|
||||
h.Unlock()
|
||||
h.mu.Unlock()
|
||||
|
||||
var handler http.Handler
|
||||
|
||||
@@ -499,9 +499,9 @@ func (h *Server) Start() error {
|
||||
select {
|
||||
// register self on interval
|
||||
case <-t.C:
|
||||
h.RLock()
|
||||
h.mu.RLock()
|
||||
registered := h.registered
|
||||
h.RUnlock()
|
||||
h.mu.RUnlock()
|
||||
rerr := config.RegisterCheck(h.opts.Context)
|
||||
// nolint: nestif
|
||||
if rerr != nil && registered {
|
||||
|
47
metadata.go
Normal file
47
metadata.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.unistack.org/micro/v4/metadata"
|
||||
)
|
||||
|
||||
type (
|
||||
rspMetadataKey struct{}
|
||||
rspMetadataVal struct {
|
||||
m metadata.Metadata
|
||||
}
|
||||
)
|
||||
|
||||
// AppendResponseMetadata adds metadata entries to metadata.Metadata stored in the context.
|
||||
// It expects the context to contain a *rspMetadataVal value under the rspMetadataKey{} key.
|
||||
// If the value is missing or invalid, the function does nothing.
|
||||
//
|
||||
// Note: this function is not thread-safe. Synchronization is required if used from multiple goroutines.
|
||||
func AppendResponseMetadata(ctx context.Context, md metadata.Metadata) {
|
||||
if md == nil {
|
||||
return
|
||||
}
|
||||
|
||||
val, ok := ctx.Value(rspMetadataKey{}).(*rspMetadataVal)
|
||||
if !ok || val == nil || val.m == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for key, values := range md {
|
||||
val.m.Append(key, values...)
|
||||
}
|
||||
}
|
||||
|
||||
// getResponseMetadata retrieves the metadata.Metadata stored in the context.
|
||||
//
|
||||
// Note: this function is not thread-safe. Synchronization is required if used from multiple goroutines.
|
||||
// If you plan to modify the returned metadata, make a full copy to avoid affecting shared state.
|
||||
func getResponseMetadata(ctx context.Context) metadata.Metadata {
|
||||
val, ok := ctx.Value(rspMetadataKey{}).(*rspMetadataVal)
|
||||
if !ok || val == nil || val.m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return val.m
|
||||
}
|
136
metadata_test.go
Normal file
136
metadata_test.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.unistack.org/micro/v4/metadata"
|
||||
)
|
||||
|
||||
func TestAppendResponseMetadata(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
md metadata.Metadata
|
||||
expected context.Context
|
||||
}{
|
||||
{
|
||||
name: "nil metadata",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: metadata.Metadata{}}),
|
||||
md: nil,
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: metadata.Metadata{}}),
|
||||
},
|
||||
{
|
||||
name: "empty metadata",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: metadata.Metadata{}}),
|
||||
md: metadata.Metadata{},
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: metadata.Metadata{}}),
|
||||
},
|
||||
{
|
||||
name: "context without response metadata key",
|
||||
ctx: context.Background(),
|
||||
md: metadata.Pairs("key1", "val1"),
|
||||
expected: context.Background(),
|
||||
},
|
||||
{
|
||||
name: "context with nil response metadata value",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, nil),
|
||||
md: metadata.Pairs("key1", "val1"),
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, nil),
|
||||
},
|
||||
{
|
||||
name: "context with incorrect type in response metadata value",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, struct{}{}),
|
||||
md: metadata.Pairs("key1", "val1"),
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, struct{}{}),
|
||||
},
|
||||
{
|
||||
name: "context with response metadata value, but nil metadata",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: nil}),
|
||||
md: metadata.Pairs("key1", "val1"),
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: nil}),
|
||||
},
|
||||
{
|
||||
name: "basic metadata append",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: metadata.Metadata{}}),
|
||||
md: metadata.Pairs("key1", "val1"),
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{
|
||||
m: metadata.Metadata{
|
||||
"key1": []string{"val1"},
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "multiple values for same key",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: metadata.Metadata{}}),
|
||||
md: metadata.Pairs("key1", "val1", "key1", "val2"),
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{
|
||||
m: metadata.Metadata{
|
||||
"key1": []string{"val1", "val2"},
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "multiple values for different keys",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: metadata.Metadata{}}),
|
||||
md: metadata.Pairs("key1", "val1", "key1", "val2", "key2", "val3", "key2", "val4", "key3", "val5"),
|
||||
expected: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{
|
||||
m: metadata.Metadata{
|
||||
"key1": []string{"val1", "val2"},
|
||||
"key2": []string{"val3", "val4"},
|
||||
"key3": []string{"val5"},
|
||||
},
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
AppendResponseMetadata(tt.ctx, tt.md)
|
||||
require.Equal(t, tt.expected, tt.ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetResponseMetadata(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
expected metadata.Metadata
|
||||
}{
|
||||
{
|
||||
name: "context without response metadata key",
|
||||
ctx: context.Background(),
|
||||
expected: nil,
|
||||
},
|
||||
{
|
||||
name: "context with nil response metadata value",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, nil),
|
||||
expected: nil,
|
||||
},
|
||||
{
|
||||
name: "context with incorrect type in response metadata value",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &struct{}{}),
|
||||
expected: nil,
|
||||
},
|
||||
{
|
||||
name: "context with response metadata value, but nil metadata",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{m: nil}),
|
||||
expected: nil,
|
||||
},
|
||||
{
|
||||
name: "valid metadata",
|
||||
ctx: context.WithValue(context.Background(), rspMetadataKey{}, &rspMetadataVal{
|
||||
m: metadata.Pairs("key1", "value1"),
|
||||
}),
|
||||
expected: metadata.Metadata{"key1": {"value1"}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.expected, getResponseMetadata(tt.ctx))
|
||||
})
|
||||
}
|
||||
}
|
45
options.go
45
options.go
@@ -31,51 +31,6 @@ func (err *Error) Error() string {
|
||||
return fmt.Sprintf("%v", err.err)
|
||||
}
|
||||
|
||||
type (
|
||||
rspCodeKey struct{}
|
||||
rspCodeVal struct {
|
||||
code int
|
||||
}
|
||||
)
|
||||
|
||||
type (
|
||||
rspHeaderKey struct{}
|
||||
rspHeaderVal struct {
|
||||
h http.Header
|
||||
}
|
||||
)
|
||||
|
||||
// SetRspHeader add response headers
|
||||
func SetRspHeader(ctx context.Context, h http.Header) {
|
||||
if rsp, ok := ctx.Value(rspHeaderKey{}).(*rspHeaderVal); ok {
|
||||
rsp.h = h
|
||||
}
|
||||
}
|
||||
|
||||
// SetRspCode saves response code in context, must be used by handler to specify http code
|
||||
func SetRspCode(ctx context.Context, code int) {
|
||||
if rsp, ok := ctx.Value(rspCodeKey{}).(*rspCodeVal); ok {
|
||||
rsp.code = code
|
||||
}
|
||||
}
|
||||
|
||||
// getRspHeader get http.Header from context
|
||||
func getRspHeader(ctx context.Context) http.Header {
|
||||
if rsp, ok := ctx.Value(rspHeaderKey{}).(*rspHeaderVal); ok {
|
||||
return rsp.h
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRspCode used internally by generated http server handler
|
||||
func GetRspCode(ctx context.Context) int {
|
||||
code := int(200)
|
||||
if rsp, ok := ctx.Value(rspCodeKey{}).(*rspCodeVal); ok {
|
||||
code = rsp.code
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
type middlewareKey struct{}
|
||||
|
||||
// Middleware passes http middlewares
|
||||
|
29
response.go
Normal file
29
response.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type (
|
||||
rspStatusCodeKey struct{}
|
||||
rspStatusCodeVal struct {
|
||||
code int
|
||||
}
|
||||
)
|
||||
|
||||
// SetResponseStatusCode sets the status code in the context.
|
||||
func SetResponseStatusCode(ctx context.Context, code int) {
|
||||
if rsp, ok := ctx.Value(rspStatusCodeKey{}).(*rspStatusCodeVal); ok {
|
||||
rsp.code = code
|
||||
}
|
||||
}
|
||||
|
||||
// GetResponseStatusCode retrieves the response status code from the context.
|
||||
func GetResponseStatusCode(ctx context.Context) int {
|
||||
code := http.StatusOK
|
||||
if rsp, ok := ctx.Value(rspStatusCodeKey{}).(*rspStatusCodeVal); ok {
|
||||
code = rsp.code
|
||||
}
|
||||
return code
|
||||
}
|
79
response_test.go
Normal file
79
response_test.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSetResponseStatusCode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
code int
|
||||
expected context.Context
|
||||
}{
|
||||
{
|
||||
name: "context without response status code key",
|
||||
ctx: context.Background(),
|
||||
code: http.StatusOK,
|
||||
expected: context.Background(),
|
||||
},
|
||||
{
|
||||
name: "context with incorrect type in response status code value",
|
||||
ctx: context.WithValue(context.Background(), rspStatusCodeKey{}, struct{}{}),
|
||||
code: http.StatusOK,
|
||||
expected: context.WithValue(context.Background(), rspStatusCodeKey{}, struct{}{}),
|
||||
},
|
||||
{
|
||||
name: "successfully set response status code",
|
||||
ctx: context.WithValue(context.Background(), rspStatusCodeKey{}, &rspStatusCodeVal{}),
|
||||
code: http.StatusOK,
|
||||
expected: context.WithValue(context.Background(), rspStatusCodeKey{}, &rspStatusCodeVal{code: http.StatusOK}),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
SetResponseStatusCode(tt.ctx, tt.code)
|
||||
require.Equal(t, tt.expected, tt.ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetResponseStatusCode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "no value in context, should return 200",
|
||||
ctx: context.Background(),
|
||||
expected: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "context with nil value",
|
||||
ctx: context.WithValue(context.Background(), rspStatusCodeKey{}, nil),
|
||||
expected: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "context with wrong type",
|
||||
ctx: context.WithValue(context.Background(), rspStatusCodeKey{}, struct{}{}),
|
||||
expected: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "context with valid status code",
|
||||
ctx: context.WithValue(context.Background(), rspStatusCodeKey{}, &rspStatusCodeVal{code: http.StatusNotFound}),
|
||||
expected: http.StatusNotFound,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.expected, GetResponseStatusCode(tt.ctx))
|
||||
})
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user