package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"

	"github.com/fastly/compute-sdk-go/fsthttp"
)

const BACKEND = "origin_0"

// Fastly only supports URL size up to 8K
// Base64 encoding will increase the body size by 30% and
// we want to leave some buffer, so set the limit to 4K
const MAX_BODY_CONVERT_SIZE = 4 * 1024

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {

		if r.Method == fsthttp.MethodPost {
			reqBody, _ := io.ReadAll(r.Body)

			if len(reqBody) > MAX_BODY_CONVERT_SIZE || len(reqBody) == 0 {
				fmt.Println("POST body too large to convert")
			} else {
				encodedBody := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(reqBody)

				r.URL.RawQuery = fmt.Sprintf("%s=%s", "postdata", encodedBody)
				r.Method = fsthttp.MethodGet
			}
  }

		resp, _ := r.Send(ctx, BACKEND)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)

	})
}