Commit | Line | Data |
---|---|---|
77e80966 JC |
1 | package genre |
2 | ||
3 | import ( | |
4 | "encoding/json" | |
5 | "git.jacobcasper.com/brackets/env" | |
6 | "git.jacobcasper.com/brackets/routes" | |
7 | "git.jacobcasper.com/brackets/types" | |
8 | "log" | |
9 | "net/http" | |
10 | ) | |
11 | ||
12 | func Index(env *env.Env) routes.Handler { | |
13 | return func(w http.ResponseWriter, r *http.Request) { | |
14 | if r.Method != "GET" { | |
15 | http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) | |
16 | return | |
17 | } | |
18 | ||
19 | w.Header().Set("Content-Type", "application/json") | |
20 | ||
21 | genreName := r.FormValue("name") | |
22 | if genreName != "" { | |
23 | genre := types.Genre{} | |
24 | row := env.Db.Db.QueryRow("SELECT ID, NAME FROM GENRE WHERE NAME = lower(?)", genreName) | |
25 | if err := row.Scan(&genre.ID, &genre.Name); err != nil { | |
26 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
27 | return | |
28 | } | |
29 | b, err := json.Marshal(genre) | |
30 | if err != nil { | |
31 | log.Print(err) | |
32 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
33 | return | |
34 | } | |
35 | w.Write(b) | |
36 | return | |
37 | } | |
38 | ||
39 | rows, err := env.Db.Db.Query("SELECT ID, NAME FROM GENRE LIMIT 20") | |
40 | if err != nil { | |
41 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
42 | return | |
43 | } | |
44 | defer rows.Close() | |
45 | ||
46 | genres := make([]types.Genre, 0) | |
47 | for rows.Next() { | |
48 | genre := types.Genre{} | |
49 | if err := rows.Scan(&genre.ID, &genre.Name); err != nil { | |
50 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
51 | return | |
52 | } | |
53 | genres = append(genres, genre) | |
54 | } | |
55 | if err = rows.Err(); err != nil { | |
56 | log.Print(err) | |
57 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
58 | return | |
59 | } | |
60 | b, err := json.Marshal(genres) | |
61 | if err != nil { | |
62 | log.Print(err) | |
63 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
64 | return | |
65 | } | |
66 | w.Write(b) | |
67 | } | |
68 | } |