feat: aliases (#5)

Reviewed-on: yw5n/yw5ncom#5
This commit is contained in:
ange 2025-04-05 10:17:05 +00:00
parent c4e53afdf1
commit abd9218561
19 changed files with 242 additions and 176 deletions

25
src/aliases.go Normal file
View file

@ -0,0 +1,25 @@
package main
import (
"log"
"os"
"strings"
)
var ALIASES map[string]string
func generateAliases() {
f, err := os.ReadFile("aliases.txt")
if err != nil {
log.Fatal(err)
}
ALIASES = make(map[string]string)
for l := range strings.SplitSeq(string(f), "\n") {
sp := strings.Fields(l)
if len(sp) == 2 {
ALIASES[sp[0]] = sp[1]
}
}
}

View file

@ -7,6 +7,7 @@ import (
func main() {
http.HandleFunc("/", route)
generateAliases()
generateTmpl()
if err := http.ListenAndServe(":3000", nil); err != nil {
log.Fatal(err)

View file

@ -17,7 +17,7 @@ var routes = []struct {
}{
{[]string{"GET"}, url(""), index},
{[]string{"GET"}, url("/static/.+"), static},
{[]string{"GET"}, url("/(.+\\.css)"), css},
{[]string{"GET"}, url("/(.+\\.(css|js))"), file},
{[]string{"GET"}, url("/([^/]+)"), html},
}
@ -42,8 +42,8 @@ func route(w http.ResponseWriter, r *http.Request) {
}
fmt.Println(r.Method, r.URL.Path)
rt.handler(w, r.WithContext(
context.WithValue(r.Context(), URLParam{}, matches[1:])),
)
context.WithValue(r.Context(), URLParam{}, matches[1:]),
))
return
}
}

View file

@ -12,10 +12,10 @@ var TMPL map[string][]byte
func generateTmpl() {
files, _ := filepath.Glob("html/*.html")
re := regexp.MustCompile("html/(.+).html")
names := make([]string, len(files))
pages := make([]string, len(files))
for i, f := range files {
names[i] = re.FindStringSubmatch(f)[1]
pages[i] = re.FindStringSubmatch(f)[1]
}
TMPL = make(map[string][]byte, len(files))
for i, f := range files {
@ -23,9 +23,9 @@ func generateTmpl() {
t, _ := template.ParseFiles(f)
t.ParseGlob("tmpl/*.tmpl")
t.Execute(b, map[string]any{
"name": names[i],
"names": names,
"page": pages[i],
"pages": pages,
})
TMPL[names[i]] = b.Bytes()
TMPL[pages[i]] = b.Bytes()
}
}

View file

@ -1,9 +1,8 @@
package main
import (
"path/filepath"
"net/http"
"fmt"
"path/filepath"
)
func index(w http.ResponseWriter, r *http.Request) {
@ -14,13 +13,14 @@ func static(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path)
}
func css(w http.ResponseWriter, r *http.Request) {
fmt.Println(filepath.Join("css", getParam(r, 0)))
http.ServeFile(w, r, filepath.Join("css", getParam(r, 0)))
func file(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join(getParam(r, 1), getParam(r, 0)))
}
func html(w http.ResponseWriter, r *http.Request) {
if t, found := TMPL[getParam(r, 0)]; found {
if a, found := ALIASES[getParam(r, 0)]; found {
http.Redirect(w, r, a, http.StatusFound)
} else if t, found := TMPL[getParam(r, 0)]; found {
w.Write(t)
} else {
http.NotFound(w, r)