main.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "fmt"
  4. "http"
  5. "template"
  6. mysql "github.com/Philio/GoMySQL"
  7. "os"
  8. )
  9. type Song struct {
  10. Yid string
  11. Name string
  12. User string
  13. }
  14. type Playlist struct {
  15. Id string
  16. Songs []*Song
  17. }
  18. var templates map[string]*template.Template
  19. const debug = true
  20. func home(w http.ResponseWriter, r *http.Request) {
  21. fmt.Fprintf(w, "path is %s", r.URL.Path[1:])
  22. }
  23. func playlist(w http.ResponseWriter, r *http.Request) {
  24. id := r.URL.Path[len("/p/"):]
  25. if len(id) != 8 {
  26. http.Redirect(w, r, "/", 303)
  27. return
  28. }
  29. db, err := mysql.DialTCP("raylu.net", "audio", "audio", "audio")
  30. if err != nil {
  31. http.Error(w, err.String(), http.StatusInternalServerError)
  32. return
  33. }
  34. query, err := db.Prepare("SELECT `yid`,`name`,`user` FROM `playlist` JOIN `song` WHERE `id` = ?;")
  35. if err != nil {
  36. http.Error(w, err.String(), http.StatusInternalServerError)
  37. return
  38. }
  39. err = query.BindParams(id)
  40. if err != nil {
  41. http.Error(w, err.String(), http.StatusInternalServerError)
  42. return
  43. }
  44. err = query.Execute()
  45. if err != nil {
  46. http.Error(w, err.String(), http.StatusInternalServerError)
  47. return
  48. }
  49. playlist := Playlist{Id: id, Songs: make([]*Song, 0, 2)}
  50. for {
  51. song := new(Song)
  52. query.BindResult(&song.Yid, &song.Name, &song.User)
  53. eof, err := query.Fetch()
  54. if err != nil {
  55. http.Error(w, err.String(), http.StatusInternalServerError)
  56. return
  57. }
  58. if eof {
  59. break
  60. }
  61. playlist.Songs = append(playlist.Songs, song)
  62. }
  63. if debug {
  64. t, err := template.ParseFile("templates/p.html", nil)
  65. if err != nil {
  66. http.Error(w, err.String(), http.StatusInternalServerError)
  67. return
  68. }
  69. err = t.Execute(w, playlist)
  70. if err != nil {
  71. w.Write([]byte(err.String()))
  72. fmt.Fprintln(os.Stderr, err.String())
  73. return
  74. }
  75. } else {
  76. err = templates["p"].Execute(w, playlist)
  77. if err != nil {
  78. fmt.Fprintln(os.Stderr, err.String())
  79. }
  80. }
  81. }
  82. func main() {
  83. templates = make(map[string]*template.Template)
  84. for _, t:= range []string{"p"} {
  85. templates[t] = template.MustParseFile("templates/" + t + ".html", nil)
  86. }
  87. http.HandleFunc("/", home)
  88. http.HandleFunc("/p/", playlist)
  89. http.ListenAndServe(":8000", nil)
  90. }