//https://developer.fastly.com/solutions/examples/regular-expression-capturing-patterns

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".
    
    // Capture a group with brackets
    re := regexp.MustCompile(`^/status/(\d+)`)
	  match := re.FindStringSubmatch(r.URL.Path)
	  fmt.Println(match[1])

    // Non-capturing groups can be created by prefixing the bracketed expression with ?:
    re = regexp.MustCompile(`^/(?:status|code)/(\d+)`)
	  match = re.FindStringSubmatch(r.URL.Path)
	  fmt.Println(match[1])

    // Bracketed character class with [...]
    re = regexp.MustCompile(`&?aaa=([^&]*)`)
	  match = re.FindStringSubmatch(r.URL.RawQuery)
	  fmt.Println(match[1])

    // Specific repeat count with {min,max}
    // Alternate options using (a|b)
    re = regexp.MustCompile(`&?a{2,6}=(foo|bar)(?:$|&)`)
	  match = re.FindStringSubmatch(r.URL.RawQuery)
	  fmt.Println(match[1])

    // Make the match case insensitive using an (?i) prefix
    re = regexp.MustCompile(`(?i)AaA=Foo`)
	  match = re.FindStringSubmatch(r.URL.RawQuery)
	  fmt.Println(match[0])
   
		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)
	})
}