// https://developer.fastly.com/solutions/examples/enable-modern-web-security-headers-to-all-responses

package main

import (
	"context"
	"fmt"
	"io"
  "strings"

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

// BackendName is the name of our service backend.
const BackendName = "origin_0"

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// This requires your service to be configured with a backend
		// named "origin_0" and pointing to "https://http-me.glitch.me".
		
    resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

    // Add web security headers.
    resp.Header.Add("content-security-policy", "default-src 'self'")
    resp.Header.Add("x-frame-options", "SAMEORIGIN")
    resp.Header.Add("x-xss-protection", "1")
    resp.Header.Add("x-content-type-options", "nosniff")
    resp.Header.Add("referrer-policy", "origin-when-cross-origin")
    resp.Header.Add("expect-ct", "enforce,max-age=30")

    // If the request uses SSL, then also add the Strict-Transport-Security header.
    if strings.HasPrefix(r.URL.String(), "https"){
      resp.Header.Add("strict-transport-security", "max-age=31536000; includeSubDomains")
    }

    // Remove response headers that do not contain the Fastly-Debug request header.
    if r.Header.Get("fastly-debug") == "" {
      resp.Header.Del("server")
      resp.Header.Del("x-powered-by")
      resp.Header.Del("x-served-by")
      resp.Header.Del("x-cache")
      resp.Header.Del("x-cache-hits")
    }

    // Remove Expires header if Cache-Control headers contains "max-age".
    if strings.Contains(resp.Header.Get("cache-control"), "max-age") {
      resp.Header.Del("expires")
    }

		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}