ツイート ブログ

GO言語でWebアプリ、ページが無い時のハンドリング

https://go.dev/doc/articles/wiki/#tmp_7

Visiting http://localhost:8080/edit/test

var validPath = regexp.MustCompile(“^/(edit|save|view)/([a-zA-Z0-9]+)$”)
// var templates = template.Must(template.ParseFiles(“tmpl/edit.html”, “tmpl/view.html”))

func getTitle(w http.ResponseWriter, r *http.Request) (string, error) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return “”, errors.New(“invalid Page Title”)
}
return m[2], nil // The title is the second subexpression.
}

func saveHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len(“/save/”):]
body := r.FormValue(“body”)
p := &Page{Title: title, Body: []byte(body)}
err := p.save()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, “/view/”+title, http.StatusFound)
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
title, err := getTitle(w, r)
if err != nil {
return
}
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, “/edit/”+title, http.StatusFound)
return
}
renderTemplate(w, “view”, p)
}

func main() {

//p1 := &Page{Title: "test", Body: []byte("This is a sample Page.")}
//p1.save()
//p2, _ := loadPage("test")
//fmt.Println(string(p2.Body))

// http.HandleFunc(“/view/”, viewHandler)

http.HandleFunc("/view/", viewHandler)
http.HandleFunc("/edit/", editHandler)
http.HandleFunc("/save/", saveHandler)

// http.HandleFunc(“/save/”, makeHandler(saveHandler))

log.Fatal(http.ListenAndServe(":8080", nil))

}

-ツイート, ブログ