// https://developer.fastly.com/solutions/examples/rewrite-url-path
package main

import (
	"context"
	"fmt"
	"io"
	"regexp"

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

// Backend is the name of our service backend.
const Backend = "origin_0"

// PathMatch matches a URL against the given pattern.
var PathMatch = regexp.MustCompile(`^/some-(custom|dynamic|complex)-pattern/url/path$`)

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Any variation of the matched path would otherwise 404.
		if PathMatch.MatchString(r.URL.Path) {
			r.URL.Path = "/status/200"
		}

		// Send the request to the named backend.
		resp, err := r.Send(ctx, Backend)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}

		// Write response to client.
		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}