diff options
author | raylu <raylu@mixpanel.com> | 2011-07-31 02:47:13 -0700 |
---|---|---|
committer | raylu <raylu@mixpanel.com> | 2011-07-31 02:47:13 -0700 |
commit | 5395b5ada15dfc417cbe789ea3297274f050892d (patch) | |
tree | 6ac4c64dcc50c29565d68e0821d0e2cdfdc6db0d /main.go | |
download | audioaxis-5395b5ada15dfc417cbe789ea3297274f050892d.tar.xz |
MySQL queries work
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 98 |
1 files changed, 98 insertions, 0 deletions
@@ -0,0 +1,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) +} |