-
Notifications
You must be signed in to change notification settings - Fork 5
/
caching_swr.go
42 lines (32 loc) · 1.11 KB
/
caching_swr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package gbox
import (
"bytes"
"context"
"fmt"
"mime"
"net/http"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func (c *Caching) swrQueryResult(ctx context.Context, result *cachingQueryResult, request *cachingRequest, handler caddyhttp.HandlerFunc) error {
buff := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buff)
buff.Reset()
rw := newCachingResponseWriter(buff)
if err := handler(rw, request.httpRequest); err != nil {
return err
}
ct := rw.Header().Get("content-type")
mt, _, _ := mime.ParseMediaType(ct)
if rw.Status() != http.StatusOK || mt != "application/json" {
return fmt.Errorf("getting invalid response from upstream, status: %d, content-type: %s", rw.Status(), ct)
}
if err := c.cachingQueryResult(ctx, request, result.plan, buff.Bytes(), rw.Header()); err != nil {
return err
}
return nil
}
func prepareSwrHTTPRequest(ctx context.Context, r *http.Request, w http.ResponseWriter) *http.Request {
s := r.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server)
return caddyhttp.PrepareRequest(r.Clone(ctx), caddy.NewReplacer(), w, s)
}