package main

import (
	"context"
	"fmt"
	"io"
	"time"

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

// 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) {
		// Set the timeout for the request to 150ms
		ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
		defer cancel()

		// Send the request to the origin server
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			// Check if the error was a deadline exceeded error
			if ctx.Err() == context.DeadlineExceeded {
				fmt.Fprintln(w, "backendResponse took more than 150ms to receive so we ignored it")
			} else {
				fmt.Fprintln(w, ctx.Err())
			}
			return
		}

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