package main
import (
	"context"
	"fmt"
	"io"
	"regexp"
	"github.com/fastly/compute-sdk-go/fsthttp"
)
const Backend = "origin_0"
const MaxRedirectCount = 2
var LocationHostPath = regexp.MustCompile(`^(?:https?://([^/]+))?(/.*)?$`)
func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		
		resp, err := r.Send(ctx, Backend)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}
    
		
		baseReq := r.Clone()
		var redirectCount int
		for isRedirect(resp.StatusCode) && redirectCount <= MaxRedirectCount {
			redirectCount++
			
			
			rc := baseReq.Clone()
			
      
			rc.URL.Path = parsePath(resp.Header.Get("Location"))
			fmt.Printf("Redirect URL (count: %d): %+v\n", redirectCount, rc.URL)
			
			resp, err = rc.Send(ctx, Backend)
			if err != nil {
				w.WriteHeader(fsthttp.StatusBadGateway)
				fmt.Fprintln(w, err)
				return
			}
		}
		
		flush(resp, w)
	})
}
func isRedirect(statusCode int) bool {
	return statusCode >= 300 && statusCode < 400
}
func parsePath(location string) (path string) {
	ss := LocationHostPath.FindStringSubmatch(location)
	
	if len(ss) >= 3 {
		path = ss[2]
	}
	
	if path == "" {
		path = "/"
	}
	return path
}
func flush(resp *fsthttp.Response, w fsthttp.ResponseWriter) {
	w.Header().Reset(resp.Header)
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}