package main

import (
	"context"
	"fmt"
	"io"
	"math/rand"
	"time"

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

// BackendNames is the slice of our service backend names.
var BackendNames = []string{"origin_0", "origin_1"}

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {

		// Select a random backend from the list of our backend names.
		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)
	})
}