package main

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

	"github.com/fastly/compute-sdk-go/fsthttp"
  "github.com/fastly/compute-sdk-go/geo"
)

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

    // Get client IP address.
    clientIP := net.ParseIP(r.RemoteAddr)
    // Lookup geo metada associated with the client IP address.
    geo, err := geo.Lookup(clientIP)
    // Return a 403 status error if the client country code matches the following codes.
    re := regexp.MustCompile(`(US|PR|AS|GU|VI)`)
    if re.MatchString(geo.CountryCode) {
      fsthttp.Error(w, "Forbidden", 403)
    }
    // Print the client country code to the console.
    fmt.Println(geo.CountryCode)

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