Skip to content

Commit

Permalink
db connection to infrastructure
Browse files Browse the repository at this point in the history
  • Loading branch information
Hiroshi Kurabayashi committed Jan 21, 2020
1 parent 3db32e9 commit 0b16fa0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 23 deletions.
5 changes: 3 additions & 2 deletions README.md
@@ -1,6 +1,7 @@
```
├── domain
│   └── model
│   └── user.go (NEW!)
├── infrastructure
│   └── datastore
│   └── dbMySQL.go (NEW!)
└── main.go (UPDATED!)
```
28 changes: 28 additions & 0 deletions infrastructure/datastore/dbMySQL.go
@@ -0,0 +1,28 @@
package datastore

import (
"fmt"

"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)

func NewMySQL() *gorm.DB {
connectString := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s%s",
"user",
"secret",
"0.0.0.0",
"3306",
"goSample",
"?charset=utf8&parseTime=True&loc=Local",
)
db, err := gorm.Open("mysql", connectString)
if err != nil {
panic(err.Error())
}
db.LogMode(true)
db.Set("gorm:table_options", "ENGIN=InnoDB")

return db
}
23 changes: 2 additions & 21 deletions main.go
Expand Up @@ -11,28 +11,9 @@ import (
"github.com/julienschmidt/httprouter"

"api/domain/model"
"api/infrastructure/datastore"
)

func connectDB() *gorm.DB {
connectString := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s%s",
"user",
"secret",
"0.0.0.0",
"3306",
"goSample",
"?charset=utf8&parseTime=True&loc=Local",
)
db, err := gorm.Open("mysql", connectString)
if err != nil {
panic(err.Error())
}
db.LogMode(true)
db.Set("gorm:table_options", "ENGIN=InnoDB")

return db
}

func setRouter(router *httprouter.Router, db *gorm.DB) {
// USER API
router.POST("/api/user/register", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
Expand Down Expand Up @@ -61,7 +42,7 @@ func setRouter(router *httprouter.Router, db *gorm.DB) {
}

func main() {
db := connectDB()
db := datastore.NewMySQL()
r := httprouter.New()
setRouter(r, db)

Expand Down

0 comments on commit 0b16fa0

Please sign in to comment.