-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (81 loc) · 2.01 KB
/
main.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
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
package main
import (
"Data"
"database/sql"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-sql-driver/mysql"
"log"
"net/http"
"os"
"strconv"
)
// database handle
var db *sql.DB
func main() {
// Capture connection properties.
cfg := mysql.Config{
User: os.Getenv("DBUSER"),
Passwd: os.Getenv("DBPASS"),
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "recordings",
}
// Get a database handle.
var err error
db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
log.Fatal(err)
}
pingErr := db.Ping()
if pingErr != nil {
log.Fatal(pingErr)
}
fmt.Println("Connected!")
//endpoints
router := gin.Default()
router.GET("/albums", getAlbums)
router.GET("/albums/:id", getAlbumByID)
router.POST("/albums", postAlbums)
router.Run("localhost:8080")
}
// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
albums, err := Data.Albums(db)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Albums found: %v\n", albums)
// return db albums
c.IndentedJSON(http.StatusOK, albums)
}
// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
var newAlbum Data.Album
// Call BindJSON to bind the received JSON to
// newAlbum.
if err := c.BindJSON(&newAlbum); err != nil {
return
}
// Add the new album to the slice.
id, err := Data.AddAlbum(newAlbum, db)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID of added album: %v\n", id)
c.IndentedJSON(http.StatusCreated, newAlbum)
}
// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
// Loop over the list of albums, looking for
// an album whose ID value matches the parameter.
alb, err := Data.AlbumByID(int64(id), db)
if err == nil {
fmt.Printf("Album found: %v\n", alb)
c.IndentedJSON(http.StatusOK, alb)
return
}
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}