daily pastebin goal
22%
SHARE
TWEET

Untitled

a guest Jun 3rd, 2018 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.         p, err := loadPage(title)
  2.         if err != nil {
  3.                 p = &Page{Title: title}
  4.         }
  5.         renderTemplate(w, "edit", p)
  6. }
  7.  
  8. func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
  9.         body := r.FormValue("body")
  10.         p := &Page{Title: title, Body: []byte(body)}
  11.         err := p.save()
  12.         if err != nil {
  13.                 log.Print(p)
  14.                 http.Error(w, err.Error(), http.StatusInternalServerError)
  15.                 return
  16.         }
  17.         http.Redirect(w, r, "/view/" + title, http.StatusFound)
  18. }
  19.  
  20. // The returned func is called a closure because it encloses values defined outside of it.  
  21. // In this case, the variable fn(the single argument to makeHandler) is enclosed by the closure.  
  22. // The variable fn will be one of our view handlers.
  23. // The closure returned be makeHandler is a function that takes an
  24. // http.ResponseWriter and http.Request (in other words, an http.HandlerFunc)
  25. func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  26.         return func(w http.ResponseWriter, r *http.Request) {
  27.                 //Here we will extract the page title from the Request,
  28.                 // and call the provided handler 'fn'
  29.                 m := validPath.FindStringSubmatch(r.URL.Path)
  30.                 if m == nil {
  31.                         http.NotFound(w, r)
  32.                         return
  33.                 }
  34.                 fn(w,r,m[2])
  35.         }
  36. }
  37.  
  38. func main() {
  39.         files, _ := ioutil.ReadDir("./")
  40.         for _, f := range files {
  41.                 log.Print(f.Name())
  42.         }
  43.         err := os.Chdir("./data/")
  44.         if err != nil {
  45.                 return  
  46.         }
  47.         http.HandleFunc("/view/", makeHandler(viewHandler))
  48.         http.HandleFunc("/edit/", makeHandler(editHandler))
  49.         http.HandleFunc("/save/", makeHandler(saveHandler))
  50.  
  51.         log.Fatal(http.ListenAndServe(":8080", nil))
  52. }
  53. -- VISUAL --                                                                 104       104,1         Bot
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top