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{} | |
9a3c373c JC |
24 | row := env.Db.Db.QueryRow(` |
25 | SELECT ID, NAME | |
26 | FROM GENRE | |
27 | WHERE NAME = lower(?)`, | |
28 | genreName, | |
29 | ) | |
77e80966 JC |
30 | if err := row.Scan(&genre.ID, &genre.Name); err != nil { |
31 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
32 | return | |
33 | } | |
34 | b, err := json.Marshal(genre) | |
35 | if err != nil { | |
36 | log.Print(err) | |
37 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
38 | return | |
39 | } | |
40 | w.Write(b) | |
41 | return | |
42 | } | |
43 | ||
9a3c373c JC |
44 | rows, err := env.Db.Db.Query(` |
45 | SELECT ID, NAME | |
46 | FROM GENRE | |
47 | LIMIT 20`, | |
48 | ) | |
77e80966 JC |
49 | if err != nil { |
50 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
51 | return | |
52 | } | |
53 | defer rows.Close() | |
54 | ||
55 | genres := make([]types.Genre, 0) | |
56 | for rows.Next() { | |
57 | genre := types.Genre{} | |
58 | if err := rows.Scan(&genre.ID, &genre.Name); err != nil { | |
59 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
60 | return | |
61 | } | |
62 | genres = append(genres, genre) | |
63 | } | |
64 | if err = rows.Err(); err != nil { | |
65 | log.Print(err) | |
66 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
67 | return | |
68 | } | |
69 | b, err := json.Marshal(genres) | |
70 | if err != nil { | |
71 | log.Print(err) | |
72 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
73 | return | |
74 | } | |
75 | w.Write(b) | |
76 | } | |
77 | } |