Untitled

mail@pastecode.io avatar
unknown
golang
16 days ago
1.8 kB
3
Indexable
Never
package api

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/go-sql-driver/mysql"
)

var db *sql.DB

func SetupDb(){
	cfg := mysql.Config{
		User:                 os.Getenv("DBUSER"),
		Passwd:               os.Getenv("DBPASS"),
		Net:                  "tcp",
		Addr:                 "127.0.0.1:3306",
		AllowNativePasswords: true,
		DBName:               "go_test",
	}

	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)
	}
}


type Album struct {
    ID     int64
    Title  string
    Artist string
    Price  float32
}


// albumsByArtist queries for albums that have the specified artist name.
func AlbumsByArtist(c *gin.Context) {
    // An albums slice to hold data from returned rows.
    var albums []Album
	name := c.Query("artist")

	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"message": "You must provide an artist",})
		return
	}
	fmt.Printf("Albums found: %v\n", albums)
	rows, err := db.Query("SELECT * FROM album WHERE artist = ?", name)
	if err != nil {
		c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
	}
	defer rows.Close()
	for rows.Next() {
		var album Album
		if err := rows.Scan(&album.ID, &album.Title, &album.Artist, &album.Price); err != nil {
			c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
		}
		albums = append(albums, album)
	}
	
	if albums != nil {
		c.IndentedJSON(http.StatusOK, albums)
	} else{
		c.IndentedJSON(http.StatusNotFound, gin.H{"message": "artist not found",})
	}
	
}




func Test(){
	fmt.Println("goodbye world")
}
Leave a Comment