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) {
resp, err := r.Send(ctx, Backend)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
switch resp.StatusCode {
case fsthttp.StatusUnavailableForLegalReasons:
h := fsthttp.NewHeader()
h.Add("Content-Type", "text/html; charset=utf-8")
resp = &fsthttp.Response{
Header: h,
StatusCode: resp.StatusCode,
Body: io.NopCloser(strings.NewReader(fmt.Sprintf(synth, resp.StatusCode))),
}
case fsthttp.StatusServiceUnavailable, fsthttp.StatusInternalServerError:
rc := r.Clone()
rc.URL.Path = "/anything/some/error/page"
originalStatus := resp.StatusCode
resp, err = rc.Send(ctx, Backend)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
resp.StatusCode = originalStatus
}
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
})
}
const synth = `
<!DOCTYPE html>
<html lang="en">
<head>
<title>There was a problem</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet" type="text/css">
<style>
body {{ display: inline-block; background: #7000f9 no-repeat; height: 100vh; margin: 0; color: white; }}
h1 {{ margin: .8em 3rem; font: 4em Roboto; }}
p {{ display: inline-block; margin: .2em 3rem; font: 2em Roboto; }}
</style>
</head>
<body>
<h1>%d APOLOGIES!</h1>
<p>Something went wrong</p>
</body>
</html>
`