package main
import (
"context"
"fmt"
"io"
"net/url"
"regexp"
"strings"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const BackendName = "origin_0"
func ValidDomain() []string{
return []string{
"example.com",
"fastly.com",
}
}
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
q, _ := url.ParseQuery(r.URL.RawQuery)
u, exist := q["url"]
if exist {
if IsValidDomain(u[0]){
fmt.Println("Valid domain.")
}else{
fmt.Println("Invalid domain.")
resp := &fsthttp.Response{
StatusCode: fsthttp.StatusForbidden,
Body: io.NopCloser(strings.NewReader("")),
}
flush(resp,w)
return
}
}else{
fmt.Println("Unable to extract domain from query string.")
resp := &fsthttp.Response{
StatusCode: fsthttp.StatusBadRequest,
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.Error())
return
}
flush(resp,w)
})
}
func IsValidDomain(d string) bool {
re := regexp.MustCompile(`^https?://([^/]*)/`)
domain := re.FindStringSubmatch(d)
for _, valid := range ValidDomain() {
if domain[1] == valid {
return true
}
}
return false
}
func flush(resp *fsthttp.Response, w fsthttp.ResponseWriter) {
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}