package main
import (
"context"
"fmt"
"io"
"strings"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const Backend = "origin_0"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
apex := "www."
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("")),
}
flush(resp, w)
return
}
resp, err := r.Send(ctx, Backend)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
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)
}