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"
"compress/gzip"
"context"
"io"
"strings"
"sync"
@ -73,8 +74,12 @@ func NewHandler(opts ...Option) *Handler {
}
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)
w := io.Writer(buf)
if md, ok := metadata.FromContext(ctx); gzipAccepted(md) && ok {
md.Set(contentEncodingHeader, "gzip")
@ -84,12 +89,10 @@ func (h *Handler) Metrics(ctx context.Context, req *codecpb.Frame, rsp *codecpb.
gz.Reset(buf)
defer gz.Close()
zw := gzip.NewWriter(buf)
defer zw.Close()
*zw = *gz
w = 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))
return nil
}
@ -105,12 +108,8 @@ func gzipAccepted(md metadata.Metadata) bool {
if !ok {
return false
}
parts := strings.Split(a, ",")
for _, part := range parts {
part = strings.TrimSpace(part)
if part == "gzip" || strings.HasPrefix(part, "gzip;") {
return true
}
if strings.Contains(a, "gzip") {
return true
}
return false
}