package main
import (
"context"
"fmt"
"net/url"
"io"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const ContentBackend = "origin_0"
const PaywallBackend = "origin_1"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
cookie, err := r.Cookie("sessionid")
if err == nil {
r.Header.Del("cookie")
r.Header.Set("auth-sessionid", cookie.Value)
}
if r.Method != "GET" && r.Method != "HEAD" {
resp, err := r.Send(ctx, ContentBackend)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err.Error())
return
}
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
return
}
r.Body = nil;
content_resp, err := r.Send(ctx, ContentBackend)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err.Error())
return
}
paywall_hdr := content_resp.Header.Get("paywall")
if content_resp.StatusCode == 403 || content_resp.StatusCode >= 500 || paywall_hdr == "" {
w.Header().Reset(content_resp.Header)
w.WriteHeader(content_resp.StatusCode)
io.Copy(w, content_resp.Body)
return
}
content_resp.Header.Del("paywall")
paywall_url, err := url.Parse(paywall_hdr)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err.Error())
return
}
if paywall_url.Host != "fiddle-paywall.glitch.me" {
w.Header().Reset(content_resp.Header)
w.WriteHeader(content_resp.StatusCode)
io.Copy(w, content_resp.Body)
return
}
req_paywall := r.Clone()
req_paywall.URL = paywall_url
paywall_resp, err := req_paywall.Send(ctx, PaywallBackend)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err.Error())
return
}
if paywall_resp.Header.Get("paywall-result") == "BLOCK" {
w.WriteHeader(fsthttp.StatusForbidden)
w.Header().Set("content-type", "text/html")
fmt.Fprintln(w, "<p>This content is only available to premium subscribers.</p>\n")
return
}
if paywall_resp.Header.Get("paywall-result") != "" {
paywall_meta := paywall_resp.Header.Get("paywall-meta")
content_resp.Header.Set("paywall-meta", paywall_meta)
}
w.Header().Reset(content_resp.Header)
w.WriteHeader(content_resp.StatusCode)
io.Copy(w, content_resp.Body)
})
}