Postingan lainnya
Error koneksi golang dengan mysql menggunakan gorm
ketika mengikuti tutorial koneksi database Golang menggunakan Gorm, saya mencobanya... tapi muncul error seperti ini
kira kira letak kesalahannya dimana ya? Terima kasih
package main
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
//Article used to declare articles models from database
type Article struct {
gorm.Model
Title string
Slug string `gorm:"unique_index"`
Desc string `sql:"type:text;"`
}
//DB is global declarated for all func
var DB *gorm.DB
func main() {
var err error
DB, err := gorm.Open("mysql", "root:@/db_train_go?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("Failed to connect database")
}
defer DB.Close()
//migrate the schema
DB.AutoMigrate(&Article{})
router := gin.Default()
apiV1 := router.Group("/api/v1/")
{
articles := apiV1.Group("/article")
{
articles.GET("/", getHome)
articles.GET("/:title", getArticle)
articles.POST("/", postArticle)
}
}
router.Run()
}
func getHome(c *gin.Context) {
var article Article
// DB.Find(&article)
DB.Find(&article)
c.JSON(200, gin.H{
"status": 200,
"data": article,
})
}
0
1 Jawaban:
Jawaban Terpilih
ternyata kesalahannya disini
DB, err := gorm.Open("mysql", "root:@/db_train_go?charset=utf8&parseTime=True&loc=Local")
seharusnya DB, err = gorm.Open("mysql", "root:@/db_train_go?charset=utf8&parseTime=True&loc=Local")
karena variabel DB dan err telah dideklarasikan
0