add gzip rsp #153 #182

Merged
vtolstov merged 6 commits from kgorbunov/micro-server-http:#153 into master 2024-03-11 12:31:20 +03:00
Showing only changes of commit aa6c32026f - Show all commits

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"context" "context"
"io"
"strings" "strings"
"sync" "sync"
@ -73,8 +74,12 @@ func NewHandler(opts ...Option) *Handler {
} }
func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.Frame) error { func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.Frame) error {
log := logger.DefaultLogger() log, ok := logger.FromContext(ctx)
if !ok {
log = logger.DefaultLogger()
}
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
w := io.Writer(buf)
if md, ok := metadata.FromContext(ctx); gzipAccepted(md) && ok { if md, ok := metadata.FromContext(ctx); gzipAccepted(md) && ok {
md.Set(contentEncodingHeader, "gzip") md.Set(contentEncodingHeader, "gzip")
@ -84,12 +89,10 @@ func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.
gz.Reset(buf) gz.Reset(buf)
defer gz.Close() defer gz.Close()
zw := gzip.NewWriter(buf) w = gz
defer zw.Close()
*zw = *gz
} }
if err := h.opts.Meter.Write(buf, h.opts.MeterOptions...); err != nil { if err := h.opts.Meter.Write(w, h.opts.MeterOptions...); err != nil {
log.Error(ctx, errors.InternalServerError(h.opts.Name, "%v", err)) log.Error(ctx, errors.InternalServerError(h.opts.Name, "%v", err))
return nil return nil
} }
@ -105,12 +108,8 @@ func gzipAccepted(md metadata.Metadata) bool {
if !ok { if !ok {
return false return false
} }
parts := strings.Split(a, ",") if strings.Contains(a, "gzip") {
for _, part := range parts { return true
part = strings.TrimSpace(part)
if part == "gzip" || strings.HasPrefix(part, "gzip;") {
return true
}
} }
return false return false
} }