cmd/stdiscosrv: Serve compressed responses

This commit is contained in:
Jakob Borg 2023-08-23 13:39:14 +02:00
parent 467522d04d
commit bdfef9010f

View File

@ -8,6 +8,7 @@ package main
import ( import (
"bytes" "bytes"
"compress/gzip"
"context" "context"
"crypto/tls" "crypto/tls"
"encoding/base64" "encoding/base64"
@ -15,6 +16,7 @@ import (
"encoding/pem" "encoding/pem"
"errors" "errors"
"fmt" "fmt"
io "io"
"log" "log"
"math/rand" "math/rand"
"net" "net"
@ -220,12 +222,21 @@ func (s *apiSrv) handleGET(ctx context.Context, w http.ResponseWriter, req *http
lookupRequestsTotal.WithLabelValues("success").Inc() lookupRequestsTotal.WithLabelValues("success").Inc()
bs, _ := json.Marshal(announcement{ w.Header().Set("Content-Type", "application/json")
Seen: time.Unix(0, rec.Seen), var bw io.Writer = w
// Use compression if the client asks for it
if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
gw := gzip.NewWriter(bw)
defer gw.Close()
bw = gw
}
json.NewEncoder(bw).Encode(announcement{
Seen: time.Unix(0, rec.Seen).Truncate(time.Second),
Addresses: addressStrs(rec.Addresses), Addresses: addressStrs(rec.Addresses),
}) })
w.Header().Set("Content-Type", "application/json")
w.Write(bs)
} }
func (s *apiSrv) handlePOST(ctx context.Context, remoteAddr *net.TCPAddr, w http.ResponseWriter, req *http.Request) { func (s *apiSrv) handlePOST(ctx context.Context, remoteAddr *net.TCPAddr, w http.ResponseWriter, req *http.Request) {