// https://developer.fastly.com/solutions/examples/search-and-replace-in-strings

package main

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

	"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) {
		// This requires your service to be configured with a backend
		// named "origin_0" and pointing to "https://http-me.glitch.me".

    // Replace multiple //// in URL paths with a single one.
    input := "/foo///bar//baz"
    re := regexp.MustCompile(`/+`)
    result := re.ReplaceAllLiteralString(input, "/")
    fmt.Println(result)

    // Remove leading www. from host header.
    input = "www.example.com"
    re = regexp.MustCompile(`^www.`)
    result = re.ReplaceAllLiteralString(input, "")
    fmt.Println(result)

    // Remove trailing slashes.
    input = "/foo/bar/"
    re = regexp.MustCompile(`/$`)
    result = re.ReplaceAllLiteralString(input, "")
    fmt.Println(result)

    // Map path parameters.
    input = "/products/furbles/12345/photos"
    re = regexp.MustCompile(`^/products/(\w+)/(\d+)(/(\w+))?$`)
    matches := re.FindStringSubmatch(input)
    result = fmt.Sprintf("/legacy.cgi?cat=%s&id=%s&page=%s", matches[1], matches[2], matches[4])
    fmt.Println(result)

		resp, err := r.Send(ctx, BackendName)
		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)
	})
}