// https://developer.fastly.com/solutions/examples/url-path-based-routing-for-microservices
package main

import (
	"context"
	"fmt"
	"io"
	"strings"

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

// Backend1 is the name of our primary service backend.
const Backend1 = "origin_0"

// Backend2 is the name of our status service backend.
const Backend2 = "origin_1"

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		if r.URL.Path == "/" {
			// Send the request to the named backend.
			resp, err := r.Send(ctx, Backend1)
			if err != nil {
				w.WriteHeader(fsthttp.StatusBadGateway)
				fmt.Fprintln(w, err)
				return
			}

			// Write response to client.
			flush(resp, w)
			return
		}

		// NOTE: For the sake of simplicity and performance we've used a string
		// comparison to check the request path, but this could incorrectly match a
		// path such as /statusFOO
		if strings.HasPrefix(r.URL.Path, "/status") {
			// Send the request to the named backend.
			resp, err := r.Send(ctx, Backend2)
			if err != nil {
				w.WriteHeader(fsthttp.StatusBadGateway)
				fmt.Fprintln(w, err)
				return
			}

			// Write response to client.
			flush(resp, w)
			return
		}

		// Generate a synthetic response.
		resp := &fsthttp.Response{
			StatusCode: fsthttp.StatusNotFound,
			Body:       io.NopCloser(strings.NewReader("The page you requested could not be found")),
		}

		// Write response to client.
		flush(resp, w)
	})
}

func flush(resp *fsthttp.Response, w fsthttp.ResponseWriter) {
	w.Header().Reset(resp.Header)
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}