package example

import (
	"fmt"
	"net/http"
)

func NewRouter() *http.ServeMux {
	return AuthLayer(
		Endpoints(),
	)
}

func AuthLayer(next http.Handler) *http.ServeMux {
	// add public patterns
	mx := http.NewServeMux()
	mx.Handle("GET /fruits", next)

	// anything else is private and requires authentication
	mx.Handle("GET /", protect(next))
	return mx
}

func protect(next http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// ... implement authorization here ...
		w.WriteHeader(http.StatusUnauthorized)
	}
}

func Endpoints() *http.ServeMux {
	mx := http.NewServeMux()
	mx.Handle("GET /fruits", fruits())
	mx.Handle("GET /keys", keys())
	return mx
}

func fruits() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "apple banana")
	}
}

func keys() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "key1 key2 key3")
	}
}
