package main

import (
	"context"
	"fmt"
	"io"

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Send a preflight request first
		req, err := fsthttp.NewRequest(fsthttp.MethodGet,
			"https://httpbin.org/response-headers?Flags=group-A,new-header,search-enabled", nil)
		if err != nil {
			w.WriteHeader(fsthttp.StatusInternalServerError)
			fmt.Fprintln(w, err.Error())
			return
		}
		resp, err := req.Send(ctx, "origin_0")
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

		// Now send the original req to content backend
		// Add flags header if received in previous response
		flags := resp.Header.Get("flags")
		if flags != "" {
			r.Header.Set("flags", flags)
		}
		resp, err = r.Send(ctx, "origin_1")
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}