package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"net/http"
	"regexp"

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		pathRx := regexp.MustCompile("/views/([^/]*)")

		m := pathRx.FindAllStringSubmatch(r.URL.Path, -1)

		if m == nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		enc := m[0][1]
		encoder := base64.URLEncoding.WithPadding(base64.NoPadding)

		dec, err := encoder.DecodeString(enc)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Printf("Error decoding path: %v\n", err)
		}

		fmt.Println("Decode path segment: ", string(dec))

		toEnc := []byte(`from=06/07/2013 query=\"Καλώς ορίσατε\"`)
		// The path segment in this demo is encoded like this
		fmt.Println("Encoded with base64.UrlEncoding: ", encoder.EncodeToString(toEnc))

		// A normal base64 encoding of the same text would include
		// characters invalid in a URL path
		fmt.Println("Encoded with base64.StdEncoding: ",base64.StdEncoding.WithPadding(base64.StdPadding).EncodeToString(toEnc))

		w.WriteHeader(http.StatusOK)
	})
}