Skip to content

Commit

Permalink
router to infrastructure
Browse files Browse the repository at this point in the history
  • Loading branch information
Hiroshi Kurabayashi committed Jan 21, 2020
1 parent 0b16fa0 commit 8128806
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 35 deletions.
4 changes: 3 additions & 1 deletion README.md
@@ -1,7 +1,9 @@
```
├── domain
├── infrastructure
│   ├── api
│   │   └── router
│   │   └── router.go (NEW!)
│   └── datastore
│   └── dbMySQL.go (NEW!)
└── main.go (UPDATED!)
```
40 changes: 40 additions & 0 deletions infrastructure/api/router/router.go
@@ -0,0 +1,40 @@
package router

import (
"encoding/json"
"fmt"
"net/http"
"strconv"

"github.com/jinzhu/gorm"
"github.com/julienschmidt/httprouter"

"api/domain/model"
)

func NewRouter(router *httprouter.Router, db *gorm.DB) {
// USER API
router.POST("/api/user/register", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
data := model.User{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
fmt.Fprintln(w, "Bad request: "+err.Error())
return
}
db.NewRecord(data)
db.Create(&data)
if db.NewRecord(data) == false {
fmt.Fprintln(w, "registerd")
}
})
router.GET("/api/user/get", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
users := model.Users{}
db.Find(&users)
json.NewEncoder(w).Encode(users)
})
router.GET("/api/user/get/:id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id, _ := strconv.Atoi(ps.ByName("id"))
user := model.User{}
db.Where("Id = ?", id).First(&user)
json.NewEncoder(w).Encode(user)
})
}
36 changes: 2 additions & 34 deletions main.go
@@ -1,50 +1,18 @@
package main

import (
"encoding/json"
"fmt"
"net/http"
"strconv"

"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/julienschmidt/httprouter"

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

func setRouter(router *httprouter.Router, db *gorm.DB) {
// USER API
router.POST("/api/user/register", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
data := model.User{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
fmt.Fprintln(w, "Bad request: "+err.Error())
return
}
db.NewRecord(data)
db.Create(&data)
if db.NewRecord(data) == false {
fmt.Fprintln(w, "registerd")
}
})
router.GET("/api/user/get", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
users := model.Users{}
db.Find(&users)
json.NewEncoder(w).Encode(users)
})
router.GET("/api/user/get/:id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id, _ := strconv.Atoi(ps.ByName("id"))
user := model.User{}
db.Where("Id = ?", id).First(&user)
json.NewEncoder(w).Encode(user)
})
}

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

defer db.Close()

Expand Down

0 comments on commit 8128806

Please sign in to comment.