// https://developer.fastly.com/solutions/examples/clean-backend-responses
package main

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

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

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

// HeaderFilters lists all header patterns that should be filtered out.
//
// NOTE: For the purposes of this example, we expect the 'Server' response header to be filtered.
var HeaderFilters = []string{
	"Fastly-Debug-",
	"Server",
	"Via",
	"X-AMZ-",
	"X-Generator",
	"X-Github-",
	"X-Goog-",
}

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Send the request to the named backend.
		resp, err := r.Send(ctx, Backend)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}

		for _, h := range resp.Header.Keys() {
			for _, f := range HeaderFilters {
				if strings.HasPrefix(h, f) {
					fmt.Println("Delete:", h)
					resp.Header.Del(h)
				}
			}
		}

		// Write response to client.
		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}