package main
import (
"context"
"fmt"
"io"
"strings"
"math/rand"
"time"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const BackendName = "origin_0"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
resp, err := r.Send(ctx, BackendName)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err.Error())
return
}
if !strings.Contains(r.Header.Get("cookie"), "_ga") {
domainsegs := len(strings.Split(r.Header.Get("host"), "."))
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
rnum := rnd.Intn(2147483647 - 1000000000 + 1) + 1000000000
ga := fmt.Sprintf("_ga=GA1.%d.%d.%d;Domain=.fiddle.fastly.dev;Max-Age=63072000;", domainsegs, rnum, time.Now().Unix())
resp.Header.Add("set-cookie", ga)
resp.Header.Set("cache-control", "no-store")
}
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
})
}