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) {
  // Set up the regular expression
	  var subdomainCheck = regexp.MustCompile(`^(.+?\.)fiddle\.`)
     // Check if the host matches the regular expression
    if (subdomainCheck.MatchString(r.Header.Get("host"))) {
      // This host has a subdomain
      // Alter the URL to a sub-folder
      r.URL.Path = "/subcontent/" + r.URL.Path;
    }

    // Get the response from the origin
		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)
	})
}