A simple pastebin application written in Go
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

70 lignes
1.4 KiB

  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "html/template"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. )
  10. func main() {
  11. // Take user input, save it
  12. http.HandleFunc("/create", createPost)
  13. // Retrieve that, display it
  14. http.HandleFunc("/post/", viewPost)
  15. // Show an editor
  16. http.HandleFunc("/", viewEditor)
  17. log.Print("Listening...")
  18. log.Fatal(http.ListenAndServe(":8888", nil))
  19. }
  20. func viewPost(w http.ResponseWriter, r *http.Request) {
  21. log.Print(r.URL.Path)
  22. id := r.URL.Path[len("/post/"):]
  23. data, err := ioutil.ReadFile(id + ".txt")
  24. if err != nil {
  25. http.Error(w, err.Error(), http.StatusInternalServerError)
  26. return
  27. }
  28. t, err := template.ParseFiles("post.html")
  29. if err != nil {
  30. http.Error(w, err.Error(), http.StatusInternalServerError)
  31. return
  32. }
  33. t.Execute(w, string(data))
  34. }
  35. func createPost(w http.ResponseWriter, r *http.Request) {
  36. log.Print(r.URL.Path)
  37. data := r.FormValue("stuff")
  38. h := md5.New()
  39. idHash := h.Sum([]byte(data))
  40. id := base64.StdEncoding.EncodeToString(idHash)[:20]
  41. err := ioutil.WriteFile(id+".txt", []byte(data), 0600)
  42. if err != nil {
  43. http.Error(w, err.Error(), http.StatusInternalServerError)
  44. return
  45. }
  46. http.Redirect(w, r, "/post/"+id, http.StatusFound)
  47. }
  48. func viewEditor(w http.ResponseWriter, r *http.Request) {
  49. log.Print(r.URL.Path)
  50. // Display editor
  51. t, err := template.ParseFiles("editor.html")
  52. if err != nil {
  53. http.Error(w, err.Error(), http.StatusInternalServerError)
  54. return
  55. }
  56. t.Execute(w, nil)
  57. }