package main
import (
	"context"
	"fmt"
	"io"
	"github.com/fastly/compute-sdk-go/fsthttp"
)
const Backend = "origin_0"
const BackendFailover = "origin_1"
func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		
		if r.Method != fsthttp.MethodGet && r.Method != fsthttp.MethodHead {
			resp, err := r.Send(ctx, Backend)
			if err != nil {
				w.WriteHeader(fsthttp.StatusBadGateway)
				fmt.Fprintln(w, err)
				return
			}
			
			flush(resp, w)
			return
		}
		
		resp, err := r.Send(ctx, Backend)
		if err != nil || isErrStatus(resp.StatusCode) {
			
			rc := r.Clone()
			
			
			
			rc.URL.Path = "/"
			
			resp, err = rc.Send(ctx, BackendFailover)
			if err != nil {
				w.WriteHeader(fsthttp.StatusBadGateway)
				fmt.Fprintln(w, err)
				return
			}
		}
		
		flush(resp, w)
	})
}
func flush(resp *fsthttp.Response, w fsthttp.ResponseWriter) {
	w.Header().Reset(resp.Header)
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}
func isErrStatus(statusCode int) bool {
	return statusCode == fsthttp.StatusForbidden || (statusCode >= 500 && statusCode < 600)
}