package main
import (
"context"
"fmt"
"net"
"math"
"github.com/fastly/compute-sdk-go/fsthttp"
"github.com/fastly/compute-sdk-go/geo"
)
const BackendName = "origin_0"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
const lat1 = 48.8566
const long1 = 2.3522
clientIP := net.ParseIP(r.RemoteAddr)
data, err := geo.Lookup(clientIP)
if err != nil {
panic(err)
}
lat2 := data.Latitude
long2 := data.Longitude
distance := haversinceDistanceBetweenPoints(lat1, long1, lat2, long2)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintln(w, fmt.Sprintf("You are %.2f km from Paris.", distance) )
w.WriteHeader(fsthttp.StatusOK)
return
})
}
func haversinceDistanceBetweenPoints(lat1, long1, lat2, long2 float64) float64 {
const R = 6371
const toRadian = math.Pi / 180
phi1 := lat1 * toRadian
phi2 := lat2 * toRadian
deltaPhi := (lat1 - lat2) * toRadian
deltaLambda := (long1 - long2) * toRadian
a := math.Pow(math.Sin(deltaPhi/2.0), 2) + math.Cos(phi1)*math.Cos(phi2)*math.Pow(math.Sin(deltaLambda/2.0), 2)
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
return R * c
}