package main
import (
"context"
"fmt"
"io"
"net/url"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const BackendName = "http_me"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
resp, err := r.Send(ctx, BackendName)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err.Error())
return
}
statusCode := resp.StatusCode;
fmt.Println("Status code:", statusCode)
switch statusCode {
case fsthttp.StatusMovedPermanently, fsthttp.StatusFound, fsthttp.StatusPermanentRedirect:
location := resp.Header.Get("location")
fmt.Println("Redirected to", location)
u, err := url.Parse(location)
if err != nil {
fsthttp.Error(w, err.Error(), fsthttp.StatusInternalServerError)
}
opts := fsthttp.NewBackendOptions()
opts.HostOverride(u.Host)
if u.Scheme == "https" {
opts.UseSSL(true)
} else {
opts.UseSSL(false)
}
fsthttp.RegisterDynamicBackend(u.Host, u.Host, opts)
newReq := r.Clone()
newReq.URL = u
resp, err = newReq.Send(ctx, u.Host)
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)
default:
}
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
})
}