I'm going to write about a function that takes all the desired content from the database. I already have something in the database
Make an interface {} variable an argument of a function with a fixed type Simple operation of "Mysql" with "Golang" x "Gorm" [Go + gin + gorm] Try adding a login function to the web application From Mysql connection in Go to data allocation to structure Oreore configuration API made with Gin and GORM
install
import (
_ "github.com/go-sql-driver/mysql"//This needs to be added by myself
"github.com/jinzhu/gorm"
)
//When not
//go get github.com/jinzhu/gorm
//go get github.com/go-sql-driver/mysql
First, connect to the database
main.go
func openGormDB() *gorm.DB { // localhost
DBMS := "mysql"
USER := "user"//mysql username
PASS := "password"//password
PROTOCOL := "tcp(localhost:3306)"
DBNAME := "sample"//Database name
CONNECT := USER + ":" + PASS + "@" + PROTOCOL + "/" + DBNAME + "?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open(DBMS, CONNECT)
if err != nil {
panic(err)
}
return db
}
This is the contents of the database
main.go
type ShiromiyaChannelInfos struct {
//ID uint64
ChannelID string
ChannelName string
ViewCount uint `gorm:"type:int"`
SubscriberCount uint `gorm:"type:int"`
VideoCount uint `gorm:"type:int"`
CreatedAt time.Time
}
Function that takes the contents of the database Write for each table
Function that takes the contents of the database
//I have to write a function like this one many times
func GetDBShiro() []ShiromiyaChannelInfos/*<=①*/ {
db := openGormDB()
var shiroInfo []ShiromiyaChannelInfos/*<=①*/
db.Find(&shiroInfo)/*<=①*/
db.Close()
return shiroInfo/*<=①*/
func GetDBHashi() []HashibaChannelInfos/*<=①*/ {
db := openGormDB()
var hashiInfo []HashibaChannelInfos/*<=①*/
db.Find(&hashiInfo)/*<=①*/
defer db.Close()
return hashiInfo/*<=①*/
}
A function that connects to a database and gets all the contents of the target table Only the place where it was different from ① above The rest is almost the same
I have to write something like the above (function that takes the contents of the database) many times, so I summarized it
main.go
//This is the finished product
func AllGetDBChannelInfo(chInfo string) (interface{}, error) {
db := openGormDB()
defer db.Close()
switch chInfo {
case "ShiromiyaChannelInfos":
var channelInfo []entity.ShiromiyaChannelInfos
db.Find(&channelInfo)
return channelInfo, nil
case "HashibaChannelInfos":
var channelInfo []entity.HashibaChannelInfos
db.Find(&channelInfo)
return channelInfo, nil
case "ChannelInfos":
var videoInfo []entity.VideoInfos
db.Find(&videoInfo)
return videoInfo, nil
default:
return nil, errors.New("That db_no name")
}
}
problem: AllGetDB must overwrite AllGetDB later when adding a function
GetDB has many functions with many duplicates. But you don't have to overwrite the function, just add it
Recommended Posts