Initial commit
This commit is contained in:
commit
2313f0f36c
6
edit.html
Normal file
6
edit.html
Normal file
@ -0,0 +1,6 @@
|
||||
<h1>Editing {{.Title}}</h1>
|
||||
|
||||
<form action="/save/{{.Title}}" method="POST">
|
||||
<div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div>
|
||||
<div><input type="submit" value="Save"></div>
|
||||
</form>
|
62
main.go
Normal file
62
main.go
Normal file
@ -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, "<h1>ERROR</h1><p>%s not found!</p>", title)
|
||||
} else {
|
||||
fmt.Fprintf(w, "<h1>%s</h1><p>%s</p>", 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))
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user