FAQ
i’m new in golan and i have built a rest API with go and mysql but the
complete code is just in one file and i’m from nodejs background and i want
to make this api according to MVC design pattern, help me plz!
My code is :

// GoMysql project main.go package main


  import (
      "strconv"


      "database/sql"
      "log"


      "github.com/gin-gonic/gin"
      _ "github.com/go-sql-driver/mysql"
      "gopkg.in/gorp.v1"
  )


  type User struct {
      Id int64 `db:"id" json:"id"`
      Firstname string `db:"firstname" json:"firstname"`
      Lastname string `db:"lastname" json:"lastname"`
  }


  //Initalize Database
  var dbmap = initDb()


  func initDb() *gorp.DbMap {
      db, err := sql.Open("mysql", "root:YES@tcp(127.0.0.1:3306)/myapi")
      checkErr(err, "sql.Open failed")
      dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB",
"UTF8"}}
      dbmap.AddTableWithName(User{}, "User").SetKeys(true, "Id")
      err = dbmap.CreateTablesIfNotExists()
      checkErr(err, "Create table failed")


      return dbmap
  }


  func checkErr(err error, msg string) {
      if err != nil {
          log.Fatalln(msg, err)
      }
  }


  func main() {
      r := gin.Default()


      route := r.Group("api/")
      {
          route.GET("/users", GetUsers)
          route.GET("/users/:id", GetUser)
          route.POST("/users", PostUser)
          route.PUT("/users/:id", UpdateUser)
          route.DELETE("/users/:id", DeleteUser)
      }


      r.Run(":8080")
  }


  //Read All
  func GetUsers(c *gin.Context) {
      var users []User
      _, err := dbmap.Select(&users, "SELECT * FROM user")


      if err == nil {
          c.JSON(200, users)
      } else {
          c.JSON(404, gin.H{"error": "no user(s) into the table"})
      }
  }


  func GetUser(c *gin.Context) {
      id := c.Params.ByName("id")
      var user User
      err := dbmap.SelectOne(&user, "SELECT * FROM user WHERE id=?", id)


      if err == nil {
          user_id, _ := strconv.ParseInt(id, 0, 64)


          content := &User{
              Id: user_id,
              Firstname: user.Firstname,
              Lastname: user.Lastname,
          }
          c.JSON(200, content)
      } else {
          c.JSON(404, gin.H{"error": "user not found"})
      }
  }


  //POST a record
  func PostUser(c *gin.Context) {
      var user User
      c.Bind(&user)


      if user.Firstname != "" && user.Lastname != "" {


          if insert, _ := dbmap.Exec(`INSERT INTO user (firstname, lastname)
VALUES (?, ?)`, user.Firstname, user.Lastname); insert != nil {
              user_id, err := insert.LastInsertId()
              if err == nil {
                  content := &User{
                      Id: user_id,
                      Firstname: user.Firstname,
                      Lastname: user.Lastname,
                  }
                  c.JSON(201, content)
              } else {
                  checkErr(err, "Insert failed")
              }
          }


      } else {
          c.JSON(422, gin.H{"error": "fields are empty"})
      }


      // curl -i -X POST -H "Content-Type: application/json" -d "{
\"firstname\": \"Thea\", \"lastname\": \"Queen\" }"
http://localhost:8080/api/v1/users
  }


  func UpdateUser(c *gin.Context) {
      id := c.Params.ByName("id")
      var user User
      err := dbmap.SelectOne(&user, "SELECT * FROM user WHERE id=?", id)


      if err == nil {
          var json User
          c.Bind(&json)


          user_id, _ := strconv.ParseInt(id, 0, 64)


          user := User{
              Id: user_id,
              Firstname: json.Firstname,
              Lastname: json.Lastname,
          }


          if user.Firstname != "" && user.Lastname != "" {
              _, err = dbmap.Update(&user)


              if err == nil {
                  c.JSON(200, user)
              } else {
                  checkErr(err, "Updated failed")
              }


          } else {
              c.JSON(422, gin.H{"error": "fields are empty"})
          }


      } else {
          c.JSON(404, gin.H{"error": "user not found"})
      }


      // curl -i -X PUT -H "Content-Type: application/json" -d "{
\"firstname\": \"Thea\", \"lastname\": \"Merlyn\" }"
http://localhost:8080/api/v1/users/1
  }


  func DeleteUser(c *gin.Context) {
      id := c.Params.ByName("id")


      var user User
      err := dbmap.SelectOne(&user, "SELECT id FROM user WHERE id=?", id)


      if err == nil {
          _, err = dbmap.Delete(&user)


          if err == nil {
              c.JSON(200, gin.H{"id #" + id: " deleted"})
          } else {
              checkErr(err, "Delete failed")
          }


      } else {
          c.JSON(404, gin.H{"error": "user not found"})
      }
  }





--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedJun 21, '15 at 2:07p
activeJun 21, '15 at 2:07p
posts1
users1
websitegolang.org

1 user in discussion

Abdul12391: 1 post

People

Translate

site design / logo © 2021 Grokbase