package main

import (
	"context"

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		if r.Method == fsthttp.MethodOptions && r.Header.Get("Origin") != "" && (r.Header.Get("access-control-request-headers") != "" || r.Header.Get("access-control-request-method") != "") {
			// Standard response to a preflight does not have a
			// response body, so a 204 No Content is appropriate,
			// though you can also send a 200 OK, that works too.
			headers := fsthttp.NewHeader()

			// Echo the requested origin back to the client.  You
			// may like to check this against an allowlist of origins
			// instead of blindly allowing potentially destructive
			// requests from any origin
			headers.Add("access-control-allow-origin", r.Header.Get("Origin"))
			headers.Add("access-control-allow-headers", r.Header.Get("access-control-request-headers"))

			// Client may use this preflight response to authorise
			// future requests that would otherwise also require a
			// preflight, so to maximise reuse, we'll list all allowed
			// methods here, not just the one that was requested.
			// (think carefully before adding 'DELETE' to this list!)
			headers.Add("access-control-allow-methods", "GET,HEAD,POST,OPTIONS")

			// Setting a cache TTL on the response allows the client
			// to use this preflight response for other requests.
			headers.Add("access-control-max-age", "86400")

			w.Header().Apply(headers)
			w.WriteHeader(fsthttp.StatusNoContent)
		} else {
			w.WriteHeader(fsthttp.StatusNotFound)
		}
	})
}