/
all-tags.go
70 lines (59 loc) · 1.37 KB
/
all-tags.go
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
package controllers
import (
"encoding/json"
"log"
"net/http"
"github.com/afonsolopez/bills/models"
"github.com/afonsolopez/bills/setup"
)
func GetAllTags(w http.ResponseWriter, r *http.Request) {
// Slice to store the response content
var res []models.Tags
// Declare all the expected results variables in order
var (
id uint
name string
)
// Query on database using the stmt SQL and passing two datetime into strings to it
rows, err := setup.DB.Query(`
SELECT DISTINCT id, name
FROM tags t2
ORDER BY name ASC
`)
if err != nil {
log.Fatal(err)
}
// Closes the rows variable section(good practice)
defer rows.Close()
// Loops over the query results
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
// log.Println(id, name)
// Generate a single Bill struct
item := models.Tags{
ID: id,
Name: name,
}
// Append this Bill struct to the response slice
res = append(res, item)
}
// Check for any erros on rolls
err = rows.Err()
if err != nil {
log.Fatal(err)
}
// Generates an Json based on the response slice
js, err := json.Marshal(res)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Set header Content-Type
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
// Write output
w.Write(js)
}