// https://developer.fastly.com/solutions/examples/add-a-new-field-to-a-json-response
package main

import (
	"context"
	"fmt"
	"io"

	"github.com/fastly/compute-sdk-go/fsthttp"
	"github.com/valyala/fastjson"
)

// BackendName is the name of our service backend.
const BackendName = "origin_0"

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Send the request to the named backend.
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}

		// Read the backend response body.
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}

		// Parse JSON response.
		var p fastjson.Parser
		v, err := p.ParseBytes(body)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}

		// Inject new JSON field.
		h := v.Get("headers")
		h.Set("new_field", fastjson.MustParse(`"data injected at the edge"`)) // must be valid JSON hence backticks around double quotes

		// Write response to client.
		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		fmt.Fprintf(w, "%s\n", v.MarshalTo(nil))
	})
}