Skip to content

Instantly share code, notes, and snippets.

@thomd
Last active September 14, 2020 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomd/da12bab55685006ce41c93686f0670e3 to your computer and use it in GitHub Desktop.
Save thomd/da12bab55685006ce41c93686f0670e3 to your computer and use it in GitHub Desktop.
Go Examples #golang #go #code
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
type Page struct {
Title string
Body []byte
}
func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func listHandler(w http.ResponseWriter, r *http.Request) {
files, _ := ioutil.ReadDir(".")
for _, file := range files {
if strings.HasSuffix(file.Name(), ".txt") {
page := strings.TrimSuffix(file.Name(), ".txt")
fmt.Fprintf(w, "<div><a href=\"/view/%s\">%[1]s</a></div>", page)
}
}
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/view/"):]
p, _ := loadPage(title)
fmt.Fprintf(w, "<h1>%s</h1><div>%s</div><div><a href=\"/edit/%s\">edit?</a></div>", p.Title, p.Body, title)
}
func saveHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/view/"):]
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
body := r.FormValue("body")
p := &Page{Title: title, Body: []byte(body)}
if err := p.save(); err != nil {
fmt.Fprintf(w, "save error: %v", err)
} else {
http.Redirect(w, r, "/view/"+title, http.StatusMovedPermanently)
}
}
func editHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/view/"):]
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title, Body: []byte("")}
}
fmt.Fprintf(w, "<h1>Editing %s</h1><form action=\"/save/%[1]s\" method=\"POST\"><textarea name=\"body\">%s</textarea><br><input type=\"submit\" value=\"Save\"></form>", p.Title, string(p.Body))
}
func main() {
http.HandleFunc("/", listHandler)
http.HandleFunc("/view/", viewHandler)
http.HandleFunc("/edit/", editHandler)
http.HandleFunc("/save/", saveHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment