// https://developer.fastly.com/solutions/examples/add-www.-to-apex-hostname-and-subdomains
package main

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

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

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		apex := "www."

		// For the purposes of the example we have the Fiddle client 
		// set a Host header without an apex for the first request.
		if !strings.HasPrefix(r.URL.Host, apex) {
			w.Header().Add("Location", fmt.Sprintf("%s%s", apex, r.URL.Host))
			w.WriteHeader(fsthttp.StatusPermanentRedirect)
			return
		}

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

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