package main

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

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

    // MustCompile() parses a regular expression and returns, if successful, 
    // a Regexp object that can be used to match against text.
    re := regexp.MustCompile(`/$`)

    // Option 1: detect trailing slash and trigger client side redirect
    // From the client prespective, this means a request ending in a 
    // slash will elicit a redirect response.
    if(re.Match([]byte(r.URL.Path))){
      // Remove trailing slashes
      NormURL := re.ReplaceAllLiteralString(r.URL.Path, "")
      h := fsthttp.NewHeader()
      h.Add("Location", NormURL)

      // Generate a synthetic response.
      resp := &fsthttp.Response{
        Header:   h,
        StatusCode: fsthttp.StatusTemporaryRedirect,
        Body: io.NopCloser(strings.NewReader("")),
      }
      // Write response to client
      flush(resp, w)
      return
    }

    // Option 2: remove the trailing slash from the request
    // From the client prespective, this means the request works whether
    // or not it ends in a slash...
    r.URL.Path = re.ReplaceAllLiteralString(r.URL.Path, "")
    
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

    // Write response to client
    flush(resp, w)
	})
}

func flush(resp *fsthttp.Response, w fsthttp.ResponseWriter) {
	w.Header().Reset(resp.Header)
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}