// https://developer.fastly.com/solutions/examples/remove-querystring-from-static-assets

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".

    // Browsers identify the intended purpose of a request via the
    // Sec-Fetch-Dest header (https://w3c.github.io/webappsec-fetch-metadata/)
    // but you should also strip querystrings from any URLs that you know
    // are not affected by querystring.

    HeaderMatch := regexp.MustCompile(`^(?:audio|audioworklet|embed|font|image|manifest|object|paintworklet|script|sharedworker|style|track|video|worker|xslt)$`)
    PathMatch := regexp.MustCompile(`(?:\.|/)(?:jpe?g|gif|png|webp|css)$`)
    if HeaderMatch.MatchString(r.Header.Get("sec-fetch-dest")) || PathMatch.MatchString(r.URL.Path) {
      // Strip querystring.
      r.URL.RawQuery = ""
    }

		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)
	})
}