// 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) {
			h := fsthttp.NewHeader()
			h.Add("Location", fmt.Sprintf("%s%s", apex, r.URL.Host))

			resp := &fsthttp.Response{
				Header:     h,
				StatusCode: fsthttp.StatusPermanentRedirect,
				Body:       io.NopCloser(strings.NewReader("")),
			}

			// Write response to client.
			flush(resp, w)
			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
		}

		// Write response to client.
		flush(resp, w)
	})
}

func flush(resp *fsthttp.Response, w fsthttp.ResponseWriter) {
	w.Header().Reset(resp.Header)
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}