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