package main
import (
	"context"
	"fmt"
	"io"
	"math/rand"
	"time"
	"github.com/fastly/compute-sdk-go/fsthttp"
)
var BackendNames = []string{"origin_0", "origin_1"}
func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		
		rand.Seed(time.Now().UnixNano())
		randIdx := rand.Intn(len(BackendNames))
		randomBackend := BackendNames[randIdx]
		fmt.Println("Sending request to backend", randomBackend)
		resp, err := r.Send(ctx, randomBackend)
		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)
	})
}