package main
import (
"context"
"fmt"
"io"
"regexp"
"strings"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const BackendName = "origin_0"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
if r.Method == "POST" {
reqBody, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(fsthttp.StatusInternalServerError)
fmt.Fprintln(w, err.Error())
return
}
re := regexp.MustCompile(`"query":\s"([^"]+)"`)
match := re.FindStringSubmatch(string(reqBody))
query := strings.ReplaceAll(match[1], "\\n", "")
r.URL.Path = "/v1/graphql"
qs := r.URL.Query()
qs.Set("query", query)
r.URL.RawQuery = qs.Encode()
r.Method = "GET"
}
resp, err := r.Send(ctx, BackendName)
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)
})
}