我會建議尋找到一些數據庫管理構架。
我個人使用gorm(github.com/jinzhu/gorm)來滿足我的數據庫需求。它具有使用結構自動創建數據庫並將其解析出來的功能。
您可以將它與「encoding/json」包配對,以將它從json傳入/傳出數據庫。
下面是一些個人的代碼,你可以將其作爲參考:
Struct:
type Application struct {
Id int64 `json:"id"`
UserID int64 `sql:"not null;" json:"user_id"`
Name string `sql:"size:255; not null; unique;" json:"name"`
ExposedPorts string `json:"exposed_ports"` //docker
DockerImage string `sql:"size:255; not null;" json:"docker_image"`
Dependencies string `json:"dependencies"`
IsEnabled bool `sql:"default:true" json:"is_enabled"`
}
JSON:
func (a *Application) GetJSON() (string, error) {
b, err := json.Marshal(a)
if err != nil {
logging.Log(err)
return "",err;
}
return string(b),err;
}
Database
//Get application information
func GetApplication(id int64) (*models.Application, error) {
app := &models.Application{}
err := db.Where(&models.Application{Id: id}).First(&app).Error
return app, err
}
func GetApplications() ([]models.Application, error) {
//Returns a list of all applications
apps := []models.Application{}
err := db.Find(&apps).Error
return apps, err
}
//delete application from database
func DeleteApplication(id int64) (bool, error) {
logging.Log("Deleting Application: ", id)
app := models.Application{}
err := db.Where(&models.Application{Id: id}).First(&app).Error
if err != nil {
return false, err
}
// TODO: Check for auth
// Delete all containers
//Delete application from database
err = db.Delete(&app).Error
if err != nil {
return false, err
}
return true, err
}
//Update Application
func UpdateApplication(app *models.Application) (bool, error) {
newapp := models.Application{}
err := db.Where(&models.Application{Id: app.Id}).First(&newapp).Error
if err != nil {
return false, err
}
err = db.Save(&app).Error
if err != nil {
return false, err
}
return true, nil
}
希望這會有所幫助:)