package main import ( "io/ioutil" "net/http" "text/template" ) func init() { http.Handle("/css/", http.FileServer(http.Dir("assets"))) http.Handle("/fonts/", http.FileServer(http.Dir("assets"))) http.HandleFunc("/index", indexHandler) http.HandleFunc("/view/", viewHandler) http.HandleFunc("/edit/", editHandler) http.HandleFunc("/del/", delHandler) http.HandleFunc("/save/", saveHandler) http.HandleFunc("/", homeHandler) } var ( indextmpl = template.Must(template.ParseFiles("tmpl/root", "tmpl/index")) viewtmpl = template.Must(template.ParseFiles("tmpl/root", "tmpl/view")) edittmpl = template.Must(template.ParseFiles("tmpl/root", "tmpl/edit")) ) func indexHandler(w http.ResponseWriter, r *http.Request) { files, err := ioutil.ReadDir("data") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } p := new(Page) for _, entry := range files { file := entry.Name() if !entry.IsDir() && file[0] != '.' { p.Pages = append(p.Pages, entry) } } p.render(w, indextmpl) } func viewHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len("/view/"):] p, err := loadPage(title) if err != nil { http.Redirect(w, r, "/edit/"+title, http.StatusFound) return } p.render(w, viewtmpl) } func editHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len("/edit/"):] p, _ := loadPage(title) p.render(w, edittmpl) } func delHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len("/del/"):] p := &Page{Title: title} if err := p.del(); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/", http.StatusFound) } func saveHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len("/save/"):] p := &Page{Title: title, Body: []byte(r.FormValue("body"))} if err := p.save(); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/view/"+title, http.StatusFound) } func homeHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/view/Home", http.StatusFound) }