package main
import (
"context"
"fmt"
"io"
"github.com/fastly/compute-sdk-go/fsthttp"
"github.com/valyala/fastjson"
)
const BackendName = "origin_0"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
resp, err := r.Send(ctx, BackendName)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
var p fastjson.Parser
v, err := p.ParseBytes(body)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
h := v.Get("headers")
h.Set("new_field", fastjson.MustParse(`"data injected at the edge"`))
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
fmt.Fprintf(w, "%s\n", v.MarshalTo(nil))
})
}