Skip to content

Instantly share code, notes, and snippets.

@yukpiz
Last active November 14, 2016 09:54
Show Gist options
  • Save yukpiz/0e58fe637166173cc2b98576f404d76e to your computer and use it in GitHub Desktop.
Save yukpiz/0e58fe637166173cc2b98576f404d76e to your computer and use it in GitHub Desktop.

go-lang, Revel, MySQL, ORM(gorm)

Installation

$ go get github.com/jinzhu/gorm
$ go get github.com/go-sql-driver/mysql

Add configuration

$ vim conf/app.conf
[dev]
db.user = root
db.password = ***
db.host = localhost
db.port = 3306
db.name = ***_development
db.protocol = tcp
db.args

Create based controller

$ vim app/controllers/database.go
package controllers

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

var Db *gorm.DB

func InitDB() {
    constr := genConStr()
    db, err := gorm.Open("mysql", constr)
    if err != nil {
        log.Panicf("Failed to database connect: %v\n", err)
    }
    db.DB()
    db.AutoMigrate(&models.User{})
    Db = db
}

func genConStr() string {
    host := getConfigString("db.host", "")
    port := getConfigString("db.port", "")
    user := getConfigString("db.user", "")
    pass := getConfigString("db.pass", "")
    name := getConfigString("db.name", "")
    prot := getConfigString("db.prot", "")
    args := getConfigString("db.args", "")
    
    if strings.Trim(args, " ") != "" {
        args = "?" + args
    } else {
        args = ""
    }
    return fmt.Sprintf("%s:%s@%s([%s]:%s)/%s%s",
        user, pass, prot, host, port, name, args)
}

func getConfigString(param string, defval string) string {
    value, found := revel.Config.String(param)
    if !found {
        if defval == "" {
            log.Panicf("Not found config parameter: %s\n", param)
        }
        return defval
    }
    return value
}

Initializer

% vim app/init.go
import (
    "{APP_PATH}/app/controllers"
)
func init() {
    revel.OnAppStart(controllers.InitDB)
}

Create models

% vim app/models/user.go
package models
type User struct {
    gorm.Model //Add fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`
    Id int64
    Name string
    Age int32
}

Existing table and that switching

$ vim app/models/user.go
package models

type User struct {..}

func (u User) TableName() string {
    if u.Role == "admin" {
        return "admin_user"
    } else {
        return "user"
    }
}

Usage from controller

% vim app/controllers/my_controller.go
import (
    "{APP_PATH}/app/models"
    "github.com/revel/revel"
)

type MyController struct {
    *revel.Controller
}

func (c MyController) Index() revel.Result {
    user := &models.User{Name: "yukpiz", Age: 68}
    Db.Create(user)
    
    result := Db.First(&user)
    return c.RenderJson(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment