summaryrefslogtreecommitdiff
path: root/allowed.go
blob: e6789206d0d502a148f5f39682e060af76db45e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"regexp"
	"slices"
)

type AllowedFiles struct {
	allowedFiles []string
}

func (a *AllowedFiles) GetFiles(w http.ResponseWriter, r *http.Request) {
	log.Println("Request for:", r.URL.String())
	url := fmt.Sprintf("static%s", r.URL.String())
	htmlRegex, err := regexp.Compile("^static/.*\\.html$")
	if err != nil {
		ErrorPage(w, 500)
		return
	}

	if url == "static/" {
		url = "static/index.html"
	}

	if !slices.Contains(a.allowedFiles, url) {
		ErrorPage(w, 404)
		return
	}

	if htmlRegex.MatchString(url) {
		t := template.Must(template.ParseFiles("templates/template.html"))

		html, err := os.ReadFile(url)
		if err != nil {
			ErrorPage(w, 500)
			return
		}

		t.Execute(w, template.HTML(html))
	} else {
		http.ServeFile(w, r, url)
	}
}