package utils
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type Album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
var Albums = []Album{
{
ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{
ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{
ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
func GetAlbums(c *gin.Context) {
i := 0
fmt.Println(i)
i += 10
fmt.Println(i)
i += 2
fmt.Println(i)
c.IndentedJSON(http.StatusOK, Albums)
}
principal
package main
import (
"github.com/gin-gonic/gin"
"go-gin/mytest/utils"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/albums", utils.GetAlbums)
router.POST("/albums", postAlbums)
router.GET("/albums:id", getAlbumByID)
router.Run("localhost:8080")
}
// 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 := c.Param("id")
// Loop over the list of albums, looking for
// an album whose ID value matches the parameter.
for _, a := range utils.Albums {
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{
"message": "album not found"})
}
// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
var newAlbum utils.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.
utils.Albums = append(utils.Albums, newAlbum)
c.IndentedJSON(http.StatusCreated, newAlbum)
}
(gdb) b utils/aa.go:24
Breakpoint 2 at 0x76fecf: file /home/rootyx/GolandProjects/go-gin/mytest/utils/aa.go, line 25.
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/rootyx/GolandProjects/go-gin/mytest/main
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7fffd0cb1700 (LWP 23828)]
[New Thread 0x7fffcbfff700 (LWP 23829)]