From 2313f0f36c0af8187bd1bb91206eac898c632d9a Mon Sep 17 00:00:00 2001 From: Johannes Rothe Date: Thu, 17 Feb 2022 22:09:03 +0100 Subject: [PATCH] Initial commit --- edit.html | 6 ++++++ go.mod | 3 +++ main.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 edit.html create mode 100644 go.mod create mode 100644 main.go diff --git a/edit.html b/edit.html new file mode 100644 index 0000000..f168d43 --- /dev/null +++ b/edit.html @@ -0,0 +1,6 @@ +

Editing {{.Title}}

+ +
+
+
+
diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4682abd --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module wiki + +go 1.17 diff --git a/main.go b/main.go new file mode 100644 index 0000000..b47b37d --- /dev/null +++ b/main.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" + "html/template" + "log" + "net/http" + "os" +) + +type Page struct { + Title string + Body []byte +} + +func loadPage(title string) (*Page, error) { + body, err := os.ReadFile(title + ".txt") + if err != nil { + return nil, err + } + return &Page{Title: title, Body: body}, nil +} + +func (p *Page) savePage() error { + filename := p.Title + ".txt" + return os.WriteFile(filename, p.Body, 0600) +} + +func viewHandler(w http.ResponseWriter, r *http.Request) { + title := r.URL.Path[len("/view/"):] + page, err := loadPage(title) + if err != nil { + fmt.Fprintf(w, "

ERROR

%s not found!

", title) + } else { + fmt.Fprintf(w, "

%s

%s

", page.Title, string(page.Body)) + } +} + +func saveHandler(w http.ResponseWriter, r *http.Request) { + title := r.URL.Path[len("/save/"):] + p := &Page{Title: title, Body: []byte(r.FormValue("body"))} + p.savePage() + http.Redirect(w, r, "/view/"+title, http.StatusFound) + +} + +func editHandler(w http.ResponseWriter, r *http.Request) { + title := r.URL.Path[len("/edit/"):] + page, err := loadPage(title) + if err != nil { + page = &Page{Title: title} + } + t, _ := template.ParseFiles("edit.html") + t.Execute(w, page) +} + +func main() { + http.HandleFunc("/view/", viewHandler) + http.HandleFunc("/save/", saveHandler) + http.HandleFunc("/edit/", editHandler) + log.Fatal(http.ListenAndServe(":8080", nil)) +}