Add index

This commit is contained in:
Johannes Rothe 2022-03-02 22:33:43 +01:00
parent a17874d5d3
commit 57f807e29f

30
main.go
View File

@ -3,9 +3,11 @@ package main
import ( import (
"fmt" "fmt"
"html/template" "html/template"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"os" "os"
"strings"
) )
type Page struct { type Page struct {
@ -54,9 +56,37 @@ func editHandler(w http.ResponseWriter, r *http.Request) {
t.Execute(w, page) t.Execute(w, page)
} }
func indexHandler(w http.ResponseWriter, r *http.Request) {
title := "index"
//template, err := template.New("index").ParseFiles("templates/index.html")
template, err := template.New("index").Parse("<!DOCTYPE html><ul>{{range $p := .}}<li><a href=view/{{$p.Title}}>{{$p.Title}}</a></li>{{end}}</ul>")
if err != nil {
fmt.Fprintf(w, "<h1>ERROR</h1><p>%s not found!</p>", title)
} else {
files, err := ioutil.ReadDir(".")
if err != nil {
log.Fatal(err)
} else {
var pages []Page
for _, file := range files {
if strings.Contains(file.Name(), ".txt") {
page, _ := loadPage(strings.Split(file.Name(), ".")[0])
pages = append(pages, *page)
}
}
err = template.Execute(w, pages)
if err != nil {
log.Fatal(err)
}
}
}
}
func main() { func main() {
http.HandleFunc("/view/", viewHandler) http.HandleFunc("/view/", viewHandler)
http.HandleFunc("/save/", saveHandler) http.HandleFunc("/save/", saveHandler)
http.HandleFunc("/edit/", editHandler) http.HandleFunc("/edit/", editHandler)
http.HandleFunc("/", indexHandler)
log.Fatal(http.ListenAndServe(":8080", nil)) log.Fatal(http.ListenAndServe(":8080", nil))
} }