package main
import (
"context"
"fmt"
"io"
"strings"
"github.com/fastly/compute-sdk-go/edgedict"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const BackendName = "origin_0"
const DictName = "redirects"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
fmt.Println("Request:", r.URL.Path)
d, err := edgedict.Open(DictName)
if err != nil {
w.WriteHeader(fsthttp.StatusInternalServerError)
fmt.Fprintln(w, err)
return
}
if v, _ := d.Get(r.URL.Path); v != "" {
h := fsthttp.NewHeader()
h.Add("Location", v)
fmt.Println("Location:", v)
resp := &fsthttp.Response{
Header: h,
StatusCode: fsthttp.StatusPermanentRedirect,
Body: io.NopCloser(strings.NewReader("")),
}
flush(resp, w)
return
}
resp, err := r.Send(ctx, BackendName)
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)
}