Compare commits

...

11 Commits
v4.1.1 ... v4

Author SHA1 Message Date
573086694b handler/meter: add HTTPHandlerFunc method
Some checks failed
coverage / build (push) Successful in 2m37s
test / test (push) Successful in 3m31s
sync / sync (push) Failing after 9s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-08-04 21:49:04 +03:00
vtolstov
3992a2bfb2 Apply Code Coverage Badge 2025-05-19 08:54:04 +00:00
b5d9fd5764 fix bug with gzip in meter handler (#223)
All checks were successful
coverage / build (push) Successful in 2m1s
test / test (push) Successful in 4m32s
2025-05-19 11:49:35 +03:00
vtolstov
39ad61b34e Apply Code Coverage Badge 2025-05-13 22:30:35 +00:00
1cb2b3c241 changed embedded mutex to private field (#222)
Some checks failed
coverage / build (push) Successful in 3m13s
test / test (push) Failing after 16m3s
2025-05-14 01:26:24 +03:00
732b5685fb update ci (#220)
All checks were successful
sync / sync (push) Successful in 10s
2025-05-05 18:01:58 +03:00
6cddb5f218 added commit hash check to avoid unnecessary repository cloning (#218)
All checks were successful
sync / sync (push) Successful in 14s
2025-05-05 14:53:15 +03:00
dd4578a57d fixup redis option parsing
All checks were successful
sync / sync (push) Successful in 17s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-05-04 14:59:50 +03:00
c6b72d7a7a check workflow
Some checks failed
sync / sync (push) Has been cancelled
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-05-04 14:41:17 +03:00
545e372b82 breaking change: modify API for working with response metadata (#213)
Some checks failed
coverage / build (push) Has been skipped
test / test (push) Successful in 3m20s
sync / sync (push) Has been cancelled
* implement functions to append/get metadata and set/get status code

* сhanged behavior to return nil instead of empty metadata for getResponseMetadata()

* сhanged work with HTTP headers to use direct array assignment instead of for-range

* fix linters

* fix meter handler

* fix uninitialized response metadata for incoming context

* removed a useless test

* metrics handler has been fixed to work with compressed data
2025-05-03 12:09:52 +03:00
d7ffae7b16 [v4] update ci (#216)
All checks were successful
sync / sync (push) Successful in 25s
* update ci

* disable coverage job && update sync job
2025-05-03 10:40:19 +03:00
14 changed files with 475 additions and 191 deletions

View File

@@ -8,8 +8,6 @@ on:
- '.gitea/**' - '.gitea/**'
pull_request: pull_request:
branches: [ main, v3, v4 ] branches: [ main, v3, v4 ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs: jobs:

View File

@@ -3,11 +3,6 @@ name: sync
on: on:
schedule: schedule:
- cron: '*/5 * * * *' - cron: '*/5 * * * *'
# push:
# branches: [ master, v3, v4 ]
# paths-ignore:
# - '.github/**'
# - '.gitea/**'
# Allows you to run this workflow manually from the Actions tab # Allows you to run this workflow manually from the Actions tab
workflow_dispatch: workflow_dispatch:
@@ -23,35 +18,77 @@ jobs:
echo "machine git.unistack.org login vtolstov password ${{ secrets.TOKEN_GITEA }}" >> /root/.netrc 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 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 - name: sync master
if: steps.check_master.outputs.sync_needed == 'true'
run: | run: |
git clone --filter=blob:none --filter=tree:0 --branch master --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo git clone --filter=blob:none --filter=tree:0 --branch master --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
cd 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 pull --rebase upstream master
git push upstream master --progress git push upstream master --progress
git push origin master --progress git push origin master --progress
cd ../ cd ../
rm -rf repo 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 - name: sync v3
if: steps.check_v3.outputs.sync_needed == 'true'
run: | run: |
git clone --filter=blob:none --filter=tree:0 --branch v3 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo git clone --filter=blob:none --filter=tree:0 --branch v3 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
cd repo cd repo
git remote add --no-tags --fetch --track v3 upstream https://github.com/${GITHUB_REPOSITORY} git remote add --no-tags --fetch --track v3 upstream https://github.com/${GITHUB_REPOSITORY}
git pull --rebase upstream v3 git pull --rebase upstream v3
git push upstream v3 git push upstream v3 --progress
git push origin v3 --progress git push origin v3 --progress
cd ../ cd ../
rm -rf repo 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 - name: sync v4
if: steps.check_v4.outputs.sync_needed == 'true'
run: | run: |
git clone --filter=blob:none --filter=tree:0 --branch v4 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo git clone --filter=blob:none --filter=tree:0 --branch v4 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
cd repo cd repo
git remote add --no-tags --fetch --track v4 upstream https://github.com/${GITHUB_REPOSITORY} git remote add --no-tags --fetch --track v4 upstream https://github.com/${GITHUB_REPOSITORY}
git pull --rebase upstream v4 git pull --rebase upstream v4
git push upstream v4 git push upstream v4 --progress
git push origin v4 --progress git push origin v4 --progress
cd ../ cd ../
rm -rf repo rm -rf repo

View File

@@ -1,5 +1,5 @@
# HTTP Server # HTTP Server
![Coverage](https://img.shields.io/badge/Coverage-3.5%25-red) ![Coverage](https://img.shields.io/badge/Coverage-5.1%25-red)
The HTTP Server is a go-micro.Server. It's a partial implementation which strips out codecs, transports, etc but enables you 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. to create a HTTP Server that could potentially be used for REST based API services.

5
go.mod
View File

@@ -1,8 +1,9 @@
module go.unistack.org/micro-server-http/v4 module go.unistack.org/micro-server-http/v4
go 1.23.0 go 1.24.0
require ( require (
github.com/stretchr/testify v1.10.0
go.unistack.org/micro-client-http/v4 v4.1.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-codec-yaml/v4 v4.1.0
go.unistack.org/micro-proto/v4 v4.1.0 go.unistack.org/micro-proto/v4 v4.1.0
@@ -12,10 +13,12 @@ require (
require ( require (
github.com/ash3in/uuidv8 v1.2.0 // indirect 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 v0.7.0 // indirect
github.com/google/gnostic-models v0.6.9 // indirect github.com/google/gnostic-models v0.6.9 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/matoous/go-nanoid v1.5.1 // 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 github.com/spf13/cast v1.7.1 // indirect
golang.org/x/sys v0.32.0 // indirect golang.org/x/sys v0.32.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250428153025-10db94c68c34 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250428153025-10db94c68c34 // indirect

View File

@@ -9,7 +9,6 @@ import (
"slices" "slices"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
"go.unistack.org/micro/v4/errors" "go.unistack.org/micro/v4/errors"
@@ -46,7 +45,6 @@ type httpHandler struct {
handlers *rhttp.Trie handlers *rhttp.Trie
name string name string
sopts server.Options sopts server.Options
sync.RWMutex
} }
func (h *httpHandler) Name() string { func (h *httpHandler) Name() string {
@@ -103,8 +101,9 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
ct = htype ct = htype
} }
ctx := context.WithValue(r.Context(), rspCodeKey{}, &rspCodeVal{}) ctx := context.WithValue(r.Context(), rspStatusCodeKey{}, &rspStatusCodeVal{})
ctx = context.WithValue(ctx, rspHeaderKey{}, &rspHeaderVal{}) ctx = context.WithValue(ctx, rspMetadataKey{}, &rspMetadataVal{m: metadata.New(0)})
md, ok := metadata.FromIncomingContext(ctx) md, ok := metadata.FromIncomingContext(ctx)
if !ok { if !ok {
md = metadata.New(len(r.Header) + 8) 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.NewIncomingContext(ctx, md)
ctx = metadata.NewOutgoingContext(ctx, metadata.New(0))
path := r.URL.Path path := r.URL.Path
@@ -257,17 +257,6 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
err = rerr.(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 return err
} }
@@ -291,19 +280,8 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
appErr := fn(ctx, hr, replyv.Interface()) appErr := fn(ctx, hr, replyv.Interface())
w.Header().Set(metadata.HeaderContentType, ct) w.Header().Set(metadata.HeaderContentType, ct)
if md, ok := metadata.FromOutgoingContext(ctx); ok { for k, v := range getResponseMetadata(ctx) {
for k, v := range md { w.Header()[k] = v
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)
}
}
} }
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct { if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
if cf, err = h.newCodec(nct); err != nil { if cf, err = h.newCodec(nct); err != nil {
@@ -332,7 +310,7 @@ func (h *Server) HTTPHandlerFunc(handler interface{}) (http.HandlerFunc, error)
return return
} }
if nscode := GetRspCode(ctx); nscode != 0 { if nscode := GetResponseStatusCode(ctx); nscode != 0 {
scode = nscode scode = nscode
} }
w.WriteHeader(scode) w.WriteHeader(scode)
@@ -351,8 +329,8 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ts := time.Now() ts := time.Now()
ctx := context.WithValue(r.Context(), rspCodeKey{}, &rspCodeVal{}) ctx := context.WithValue(r.Context(), rspStatusCodeKey{}, &rspStatusCodeVal{})
ctx = context.WithValue(ctx, rspHeaderKey{}, &rspHeaderVal{}) ctx = context.WithValue(ctx, rspMetadataKey{}, &rspMetadataVal{m: metadata.New(0)})
md, ok := metadata.FromIncomingContext(ctx) md, ok := metadata.FromIncomingContext(ctx)
if !ok { if !ok {
@@ -373,10 +351,11 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
md["Proto"] = append(md["Proto"], r.Proto) md["Proto"] = append(md["Proto"], r.Proto)
md["Content-Length"] = append(md["Content-Length"], fmt.Sprintf("%d", r.ContentLength)) md["Content-Length"] = append(md["Content-Length"], fmt.Sprintf("%d", r.ContentLength))
if len(r.TransferEncoding) > 0 { 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["Host"] = append(md["Host"], r.Host)
md["RequestURI"] = append(md["RequestURI"], r.RequestURI) md["RequestURI"] = append(md["RequestURI"], r.RequestURI)
ctx = metadata.NewIncomingContext(ctx, md) ctx = metadata.NewIncomingContext(ctx, md)
ctx = metadata.NewOutgoingContext(ctx, metadata.New(0)) ctx = metadata.NewOutgoingContext(ctx, metadata.New(0))
@@ -442,7 +421,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
), ),
) )
defer func() { defer func() {
n := GetRspCode(ctx) n := GetResponseStatusCode(ctx)
if s, _ := sp.Status(); s != tracer.SpanStatusError && n > 399 { if s, _ := sp.Status(); s != tracer.SpanStatusError && n > 399 {
sp.SetStatus(tracer.SpanStatusError, http.StatusText(n)) 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() h.opts.Meter.Counter(semconv.ServerRequestInflight, "endpoint", endpointName, "server", "http").Inc()
defer func() { defer func() {
n := GetRspCode(ctx) n := GetResponseStatusCode(ctx)
if n > 399 { if n > 399 {
h.opts.Meter.Counter(semconv.ServerRequestTotal, "endpoint", endpointName, "server", "http", "status", "success", "code", strconv.Itoa(n)).Inc() h.opts.Meter.Counter(semconv.ServerRequestTotal, "endpoint", endpointName, "server", "http", "status", "success", "code", strconv.Itoa(n)).Inc()
} else { } else {
@@ -482,7 +461,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
) )
defer func() { defer func() {
if n := GetRspCode(ctx); n > 399 { if n := GetResponseStatusCode(ctx); n > 399 {
sp.SetStatus(tracer.SpanStatusError, http.StatusText(n)) sp.SetStatus(tracer.SpanStatusError, http.StatusText(n))
} else { } else {
sp.SetStatus(tracer.SpanStatusError, http.StatusText(http.StatusNotFound)) 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.Histogram(semconv.ServerRequestDurationSeconds, "endpoint", handler.name, "server", "http").Update(te.Seconds())
h.opts.Meter.Counter(semconv.ServerRequestInflight, "endpoint", handler.name, "server", "http").Dec() h.opts.Meter.Counter(semconv.ServerRequestInflight, "endpoint", handler.name, "server", "http").Dec()
n := GetRspCode(ctx) n := GetResponseStatusCode(ctx)
if n > 399 { if n > 399 {
h.opts.Meter.Counter(semconv.ServerRequestTotal, "endpoint", handler.name, "server", "http", "status", "failure", "code", strconv.Itoa(n)).Inc() h.opts.Meter.Counter(semconv.ServerRequestTotal, "endpoint", handler.name, "server", "http", "status", "failure", "code", strconv.Itoa(n)).Inc()
} else { } else {
@@ -531,7 +510,7 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
defer func() { defer func() {
n := GetRspCode(ctx) n := GetResponseStatusCode(ctx)
if n > 399 { if n > 399 {
if s, _ := sp.Status(); s != tracer.SpanStatusError { if s, _ := sp.Status(); s != tracer.SpanStatusError {
sp.SetStatus(tracer.SpanStatusError, http.StatusText(n)) sp.SetStatus(tracer.SpanStatusError, http.StatusText(n))
@@ -625,17 +604,6 @@ func (h *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err = rerr.(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)
if err != nil && sp != nil { if err != nil && sp != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error()) 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()) appErr := fn(ctx, hr, replyv.Interface())
w.Header().Set(metadata.HeaderContentType, ct) w.Header().Set(metadata.HeaderContentType, ct)
if md, ok := metadata.FromOutgoingContext(ctx); ok { for k, v := range getResponseMetadata(ctx) {
for k, v := range md { w.Header()[k] = v
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)
}
}
} }
if nct := w.Header().Get(metadata.HeaderContentType); nct != ct { if nct := w.Header().Get(metadata.HeaderContentType); nct != ct {
if cf, err = h.newCodec(nct); err != nil { 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) handler.sopts.Logger.Error(handler.sopts.Context, "handler error", err)
} }
scode = http.StatusInternalServerError scode = http.StatusInternalServerError
} else if nscode := GetRspCode(ctx); nscode != 0 { } else if nscode := GetResponseStatusCode(ctx); nscode != 0 {
scode = nscode scode = nscode
} }

View File

@@ -4,11 +4,14 @@ import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"context" "context"
"fmt"
"io" "io"
http "net/http"
"strings" "strings"
"sync" "sync"
codecpb "go.unistack.org/micro-proto/v4/codec" 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/logger"
"go.unistack.org/micro/v4/metadata" "go.unistack.org/micro/v4/metadata"
"go.unistack.org/micro/v4/meter" "go.unistack.org/micro/v4/meter"
@@ -84,36 +87,87 @@ func NewHandler(opts ...Option) *Handler {
return &Handler{Options: options} return &Handler{Options: options}
} }
func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.Frame) error { func (h *Handler) HTTPHandlerFunc(w http.ResponseWriter, r *http.Request) {
log, ok := logger.FromContext(ctx) var wr io.Writer
if !ok { if v := r.Header.Get(acceptEncodingHeader); strings.Contains(v, "gzip") && !h.Options.DisableCompress {
log = logger.DefaultLogger w.Header().Add(contentEncodingHeader, "gzip")
}
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
buf.Reset()
w := io.Writer(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) gz := gzipPool.Get().(*gzip.Writer)
defer gzipPool.Put(gz) defer gzipPool.Put(gz)
gz.Reset(w) gz.Reset(w)
defer gz.Close() defer gz.Close()
w = gz wr = gz
gz.Flush() } else {
wr = w
} }
if err := h.Options.Meter.Write(w, h.Options.MeterOptions...); err != nil { if err := h.Options.Meter.Write(wr, h.Options.MeterOptions...); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
// gz.Flush() must be called after writing metrics to ensure buffered data is written to the underlying writer.
if gz, ok := wr.(*gzip.Writer); ok {
gz.Flush()
}
}
func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.Frame) error {
log, ok := logger.FromContext(ctx)
if !ok {
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) log.Error(ctx, "http/meter write failed", err)
}
return nil 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()
gz := gzipPool.Get().(*gzip.Writer)
defer gzipPool.Put(gz)
gz.Reset(buf)
if err := h.Options.Meter.Write(gz, h.Options.MeterOptions...); err != nil {
return fmt.Errorf("meter write: %w", err)
}
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() rsp.Data = buf.Bytes()
return nil return nil

View File

@@ -1,11 +0,0 @@
package http
import (
"context"
"testing"
)
func TestHandler(t *testing.T) {
ctx := context.WithValue(context.TODO(), rspCodeKey{}, &rspCodeVal{})
SetRspCode(ctx, 404)
}

80
http.go
View File

@@ -36,7 +36,7 @@ type Server struct {
stateReady *atomic.Uint32 stateReady *atomic.Uint32
stateHealth *atomic.Uint32 stateHealth *atomic.Uint32
registerRPC bool registerRPC bool
sync.RWMutex mu sync.RWMutex
registered bool registered bool
init bool init bool
} }
@@ -45,9 +45,9 @@ func (h *Server) newCodec(ct string) (codec.Codec, error) {
if idx := strings.IndexRune(ct, ';'); idx >= 0 { if idx := strings.IndexRune(ct, ';'); idx >= 0 {
ct = ct[:idx] ct = ct[:idx]
} }
h.RLock() h.mu.RLock()
cf, ok := h.opts.Codecs[ct] cf, ok := h.opts.Codecs[ct]
h.RUnlock() h.mu.RUnlock()
if ok { if ok {
return cf, nil return cf, nil
} }
@@ -55,9 +55,9 @@ func (h *Server) newCodec(ct string) (codec.Codec, error) {
} }
func (h *Server) Options() server.Options { func (h *Server) Options() server.Options {
h.Lock() h.mu.Lock()
opts := h.opts opts := h.opts
h.Unlock() h.mu.Unlock()
return opts return opts
} }
@@ -66,7 +66,7 @@ func (h *Server) Init(opts ...server.Option) error {
return nil return nil
} }
h.Lock() h.mu.Lock()
for _, o := range opts { for _, o := range opts {
o(&h.opts) o(&h.opts)
@@ -89,41 +89,41 @@ func (h *Server) Init(opts ...server.Option) error {
for pm, ps := range phs.h { for pm, ps := range phs.h {
for pp, ph := range ps { for pp, ph := range ps {
if err := h.pathHandlers.Insert([]string{pm}, pp, ph); err != nil { if err := h.pathHandlers.Insert([]string{pm}, pp, ph); err != nil {
h.Unlock() h.mu.Unlock()
return err return err
} }
} }
} }
} }
h.Unlock() h.mu.Unlock()
h.RLock() h.mu.RLock()
if err := h.opts.Register.Init(); err != nil { if err := h.opts.Register.Init(); err != nil {
h.RUnlock() h.mu.RUnlock()
return err return err
} }
if err := h.opts.Broker.Init(); err != nil { if err := h.opts.Broker.Init(); err != nil {
h.RUnlock() h.mu.RUnlock()
return err return err
} }
if err := h.opts.Tracer.Init(); err != nil { if err := h.opts.Tracer.Init(); err != nil {
h.RUnlock() h.mu.RUnlock()
return err return err
} }
if err := h.opts.Logger.Init(); err != nil { if err := h.opts.Logger.Init(); err != nil {
h.RUnlock() h.mu.RUnlock()
return err return err
} }
if err := h.opts.Meter.Init(); err != nil { if err := h.opts.Meter.Init(); err != nil {
h.RUnlock() h.mu.RUnlock()
return err return err
} }
h.RUnlock() h.mu.RUnlock()
h.Lock() h.mu.Lock()
h.init = true h.init = true
h.Unlock() h.mu.Unlock()
return nil return nil
} }
@@ -132,27 +132,27 @@ func (h *Server) Handle(handler server.Handler) error {
// passed unknown handler // passed unknown handler
hdlr, ok := handler.(*httpHandler) hdlr, ok := handler.(*httpHandler)
if !ok { if !ok {
h.Lock() h.mu.Lock()
h.hd = handler h.hd = handler
h.Unlock() h.mu.Unlock()
return nil return nil
} }
// passed http.Handler like some muxer // passed http.Handler like some muxer
if _, ok := hdlr.hd.(http.Handler); ok { if _, ok := hdlr.hd.(http.Handler); ok {
h.Lock() h.mu.Lock()
h.hd = handler h.hd = handler
h.Unlock() h.mu.Unlock()
return nil return nil
} }
// passed micro compat handler // passed micro compat handler
h.Lock() h.mu.Lock()
if h.handlers == nil { if h.handlers == nil {
h.handlers = make(map[string]server.Handler) h.handlers = make(map[string]server.Handler)
} }
h.handlers[handler.Name()] = handler h.handlers[handler.Name()] = handler
h.Unlock() h.mu.Unlock()
return nil return nil
} }
@@ -294,10 +294,10 @@ func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) s
} }
func (h *Server) Register() error { func (h *Server) Register() error {
h.RLock() h.mu.RLock()
rsvc := h.rsvc rsvc := h.rsvc
config := h.opts config := h.opts
h.RUnlock() h.mu.RUnlock()
// if service already filled, reuse it and return early // if service already filled, reuse it and return early
if rsvc != nil { if rsvc != nil {
@@ -312,9 +312,9 @@ func (h *Server) Register() error {
return err return err
} }
h.RLock() h.mu.RLock()
registered := h.registered registered := h.registered
h.RUnlock() h.mu.RUnlock()
if !registered { if !registered {
if config.Logger.V(logger.InfoLevel) { if config.Logger.V(logger.InfoLevel) {
@@ -332,19 +332,19 @@ func (h *Server) Register() error {
return nil return nil
} }
h.Lock() h.mu.Lock()
h.registered = true h.registered = true
h.rsvc = service h.rsvc = service
h.Unlock() h.mu.Unlock()
return nil return nil
} }
func (h *Server) Deregister() error { func (h *Server) Deregister() error {
h.RLock() h.mu.RLock()
config := h.opts config := h.opts
h.RUnlock() h.mu.RUnlock()
service, err := server.NewRegisterService(h) service, err := server.NewRegisterService(h)
if err != nil { if err != nil {
@@ -359,24 +359,24 @@ func (h *Server) Deregister() error {
return err return err
} }
h.Lock() h.mu.Lock()
h.rsvc = nil h.rsvc = nil
if !h.registered { if !h.registered {
h.Unlock() h.mu.Unlock()
return nil return nil
} }
h.registered = false h.registered = false
h.Unlock() h.mu.Unlock()
return nil return nil
} }
func (h *Server) Start() error { func (h *Server) Start() error {
h.RLock() h.mu.RLock()
config := h.opts config := h.opts
h.RUnlock() h.mu.RUnlock()
// micro: config.Transport.Listen(config.Address) // micro: config.Transport.Listen(config.Address)
var ts net.Listener var ts net.Listener
@@ -406,9 +406,9 @@ func (h *Server) Start() error {
config.Logger.Info(config.Context, "Listening on "+ts.Addr().String()) config.Logger.Info(config.Context, "Listening on "+ts.Addr().String())
} }
h.Lock() h.mu.Lock()
h.opts.Address = ts.Addr().String() h.opts.Address = ts.Addr().String()
h.Unlock() h.mu.Unlock()
var handler http.Handler var handler http.Handler
@@ -499,9 +499,9 @@ func (h *Server) Start() error {
select { select {
// register self on interval // register self on interval
case <-t.C: case <-t.C:
h.RLock() h.mu.RLock()
registered := h.registered registered := h.registered
h.RUnlock() h.mu.RUnlock()
rerr := config.RegisterCheck(h.opts.Context) rerr := config.RegisterCheck(h.opts.Context)
// nolint: nestif // nolint: nestif
if rerr != nil && registered { if rerr != nil && registered {

47
metadata.go Normal file
View 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
View 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))
})
}
}

View File

@@ -31,51 +31,6 @@ func (err *Error) Error() string {
return fmt.Sprintf("%v", err.err) 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{} type middlewareKey struct{}
// Middleware passes http middlewares // Middleware passes http middlewares

29
response.go Normal file
View 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
View 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))
})
}
}