package main

import (
	"context"
	"fmt"
	"net"

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		if r.URL.Path == "/log" {
			// Consider enriching the client-submitted data with extra stuff
			client_geo, err := geo.Lookup(net.ParseIP(r.RemoteAddr))
			if err != nil {
				fmt.Print(err)
				w.WriteHeader(fsthttp.StatusInternalServerError)
				fmt.Fprint(w, "GEO Lookup Error: ", err)
				return
			}

			query := r.URL.Query()
			query.Add("clientCity", client_geo.City)
			r.URL.RawQuery = query.Encode()

			// Submit the final set of data (querystring only) as a log line
			// (ensure that 's3_rum_data' or equivalent log endpoint is configured
			// on your service)
			endpoint := rtlog.Open("s3_rum_data")
			fmt.Fprintln(endpoint, r.URL.RawQuery)

			w.WriteHeader(fsthttp.StatusNoContent)
			return
		}

		w.WriteHeader(fsthttp.StatusNotFound)
	})
}