// https://developer.fastly.com/solutions/examples/filter-cookies-or-other-structured-headers

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".

    // Store individual cookie values in a slice delimited by ; 
    cookies := strings.Split(r.Header.Values("cookie")[0], "; ")
    // Define a slice of values to keep. 
    keep := []string{"name2", "name3", "name6"}
    result := FilterExcept(cookies, keep)
    // Put the filtered values back into the header.
    r.Header.Set("cookie", result)

		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)
	})
}

// FilterExcept() function takes in an input and a list
// of parameters to keep and returns a string containing
// the parameters to keep.
func FilterExcept(input []string, keep []string) string {
  var result string
	for _, val := range keep {
		for index, element := range input {
			if strings.Contains(element, val) {
				// Stash the values back into a string.
        if index < len(input)-1 {
					result += element + "; "
				} else {
					result += element
				}
			}
		}
	}
	return result
}