Skip to content

Instantly share code, notes, and snippets.

@gboncoffee
Created June 23, 2024 22:34
Show Gist options
  • Save gboncoffee/ec5f71206d5ec0d79b9fc54c87095673 to your computer and use it in GitHub Desktop.
Save gboncoffee/ec5f71206d5ec0d79b9fc54c87095673 to your computer and use it in GitHub Desktop.
Example of a minimal wiki web app with only Go's standard library
<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>
package main
import (
"errors"
"html/template"
"log"
"net/http"
"os"
"regexp"
)
var templates = template.Must(template.ParseFiles("edit.html", "view.html"))
var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
type Page struct {
Title string
Body []byte
}
func (p *Page) Save() error {
fileName := p.Title + ".txt"
return os.WriteFile(fileName, p.Body, 0600)
}
func LoadPage(title string) (*Page, error) {
fileName := title + ".txt"
body, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func GetTitle(writer http.ResponseWriter, request *http.Request) (string, error) {
match := validPath.FindStringSubmatch(request.URL.Path)
if match == nil {
http.NotFound(writer, request)
return "", errors.New("invalid Page Title")
}
return match[2], nil // The title is the second subexpression.
}
func ViewHandler(writer http.ResponseWriter, request *http.Request) {
title, err := GetTitle(writer, request)
if err != nil {
return
}
page, err := LoadPage(title)
if err != nil {
http.Redirect(writer, request, "/edit/"+title, http.StatusFound)
return
}
templates.ExecuteTemplate(writer, "view.html", page)
}
func EditHandler(writer http.ResponseWriter, request *http.Request) {
title, err := GetTitle(writer, request)
if err != nil {
return
}
page, err := LoadPage(title)
if err != nil {
page = &Page{Title: title}
}
templates.ExecuteTemplate(writer, "edit.html", page)
}
func SaveHandler(writer http.ResponseWriter, request *http.Request) {
title, err := GetTitle(writer, request)
if err != nil {
return
}
body := request.FormValue("body")
page := &Page{Title: title, Body: []byte(body)}
err = page.Save()
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(writer, request, "/view/"+title, http.StatusFound)
}
func main() {
http.HandleFunc("/view/", ViewHandler)
http.HandleFunc("/edit/", EditHandler)
http.HandleFunc("/save/", SaveHandler)
log.Fatal(http.ListenAndServe(":6969", nil))
}
<h1>{{.Title}}</h1>
<p>[<a href="/edit/{{.Title}}">edit</a>]</p>
<div>{{printf "%s" .Body}}</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment