root: redirect user to destination

Amolith created

Implements: https://todo.sr.ht/~amolith/public-tracker/9

Change summary

root.go | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)

Detailed changes

root.go 🔗

@@ -5,12 +5,34 @@ import (
 	"io"
 	"log"
 	"net/http"
+	"strings"
 	"text/template"
 
 	"github.com/dgraph-io/badger/v3"
 )
 
 func (m model) root(writer http.ResponseWriter, request *http.Request) {
+	path := request.URL.Path
+	if path != "/" {
+		destinationKey := strings.TrimPrefix(path, "/")
+		err := m.database.View(func(txn *badger.Txn) error {
+			destinationEntry, err := txn.Get([]byte(destinationKey))
+			if err == nil {
+				destinationValue, err := destinationEntry.ValueCopy(nil)
+				if err != nil {
+					return err
+				}
+				log.Println("Redirecting visitor to '" + string(destinationValue) + "'")
+				http.Redirect(writer, request, string(destinationValue), 302)
+			}
+			return err
+		})
+		if err != nil {
+			io.WriteString(writer, string(err.Error()))
+		}
+		return
+	}
+
 	cookie, err := request.Cookie("access_token")
 	if err != nil {
 		home, err := templates.ReadFile("templates/home_unauthenticated.html")