package main
import (
"context"
"fmt"
"io"
"math"
"net"
"strconv"
"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) {
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
}
offset := client_geo.UTCOffset
r.Header.Add("tz-offset-iso8601", strconv.Itoa(offset))
tz_hour := int(math.Round(float64(offset) / 100))
r.Header.Add("tz-hour", strconv.Itoa(tz_hour))
tz_offset_hours := int(float64(offset%100)/60.0 + math.Round(float64(offset)/100.0))
r.Header.Add("tz-offset-hours", strconv.Itoa(tz_offset_hours))
tz_evenhour := int(math.Round(float64(offset)/100/2) * 2)
r.Header.Add("tz-evenhour", strconv.Itoa(tz_evenhour))
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)
})
}