package main

import (
	"context"
	"fmt"
	"io"
  "net"
  "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".
    
    // Extract IP from header.
    ip := r.Header.Get("fastly-client-ip")
    // checkIPAddress() function checks IP validity and IP type.
    checkIPAddressType(ip)

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

func checkIPAddressType(ip string) {
  // ParseIP() checks if the IP is valid. Returns nil if it is invalid.
  if net.ParseIP(ip) == nil {
    fmt.Println("Invalid IP:", ip)
    return
  }
  // Check IP version.
  if strings.Contains(ip, "."){
    fmt.Println("IPv4:", ip)
    return
  }else{
    fmt.Println("IPv6:", ip)
    return
  }
}