[Go] RevelでMySQLを操作

conf/app.conf

db.user = fuga
db.password = hoge
db.host = localhost
db.port = 3306
db.name = test
db.protocol = tcp

app/controllers/gorm.go

package controllers

import (
	"github.com/revel/revel"
	"github.com/jinzhu/gorm"
	"strings"
	"fmt"
	_"github.com/go-sql-driver/mysql"
)

var DB *gorm.DB


func InitDB(){
	db, err := gorm.Open("mysql", getConnectionString())

	if err != nil {
		panic(err.Error())
	}

	db.DB()
	DB = db
}


func getParamString(param string, defaultValue string) string {
	p, found := revel.Config.String(param)
	if !found {
		if defaultValue == "" {
			fmt.Sprintf("Could not find parameter: " + param)
		} else {
			return defaultValue
		}
	}
	return p
}


func getConnectionString() string {
	host := getParamString("db.host", "localhost")
	port := getParamString("db.port", "3306")
	user := getParamString("db.user", "root")
	pass := getParamString("db.password", "password")
	dbname := getParamString("db.name", "test")
	protocol := getParamString("db.protocol", "tcp")
	dbargs := getParamString("dbargs", "	")
	timezone := getParamString("db.timezone", "parseTime=True")

	if strings.Trim(dbargs, " ") != ""{
		dbargs = "?" + dbargs
	} else {
		dbargs = ""
	}

	return fmt.Sprintf("%s:%s@%s([%s]:%s)/%s?%s", user, pass, protocol, host, port, dbname, timezone)
}

app/models/idols.go

package models

type Idols struct {
	ID int
	Name string `json:"name"`
	Label string `json:"label"`
	Producer string `json:"producer"`
	birth string `json:"birth"`
	Member string `json:"member"`
	Song string `json:"song"`
}

app/controllers/app.go

package controllers

import (
	"github.com/revel/revel"
	"myapp/app/models"
	_"github.com/go-sql-driver/mysql"
)

type App struct {
	*revel.Controller
}

func (c App) Index() revel.Result {

	result := []models.Idols{}
	DB.Where("id = ?", 1).First(&result)
	greeting := result[0].Name
	
	return c.Render(greeting)
}

### 更新

	result := models.Idols{}
	DB.First(&result, 5)
	result.Song = "flash"
	DB.Save(&result)

大体わかった
後はデモを作るか topicは野球あたりにしましょう