go练习:实现mysql+ORM+restful api
Posted MapReduce Raft /Java Go Rust
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go练习:实现mysql+ORM+restful api相关的知识,希望对你有一定的参考价值。
本章用于练习go的模块管理
1.在gopath外新建目录smart4go
2.进入目录,创建mod
go mod init smart4go
3.拉取依赖模块
go get -u github.com/emicklei/go-restful
go get -u github.com/go-sql-driver/mysql
go get -u github.com/jinzhu/gorm
4.写一个main.go测试一下
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "log" ) var db *gorm.DB var err error var dbDriver = "mysql" var dbUser = "your_user_name" var dbPass = "your_password" var dbName = "your_db" var tcp = "tcp(localhost:3306)" func main() { db, err = gorm.Open(dbDriver, dbUser+":"+dbPass+"@"+tcp+"/"+dbName) if err != nil { log.Println("Connection Failed to Open:", err) } else { log.Println("Connection Established") } defer db.Close() }
成功建立连接
创建测试表
CREATE TABLE `t_user` ( `id` int(11) NOT NULL auto_increment, `name` varchar(255) DEFAULT NULL, `city` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB
我的练习
package main import ( "github.com/emicklei/go-restful" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "log" "net/http" ) // mysql> desc t_user; // +-------+--------------+------+-----+---------+----------------+ // | Field | Type | Null | Key | Default | Extra | // +-------+--------------+------+-----+---------+----------------+ // | id | int(11) | NO | PRI | NULL | auto_increment | // | name | varchar(255) | YES | | NULL | | // | city | varchar(255) | YES | | NULL | | // | age | int(11) | YES | | NULL | | // +-------+--------------+------+-----+---------+----------------+ type User struct { Id int `json:"id"` Name string `json:"name"` City string `json:"city"` Age int `json:"age"` } var users []User var dbDriver = "mysql" var dbUser = "****" var dbPass = "***" var dbName = "test" var tcp = "tcp(localhost:3306)" type UserResource struct { db *gorm.DB } func (u UserResource) Register(container *restful.Container) { ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well ws.Route(ws.GET("/{id}").To(u.findUser)) ws.Route(ws.POST("/").To(u.createUser)) ws.Route(ws.PUT("/{id}").To(u.updateUser)) ws.Route(ws.DELETE("/{id}").To(u.removeUser)) container.Add(ws) } // GET http://localhost:8080/users/1 // func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("id") u.db.Where("id = ?", id).Find(&users) if users == nil || len(users) < 1 { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusNotFound, "User could not be found.") } else { response.WriteEntity(users) } } // POST http://localhost:8080/users // <User><Id>1</Id><Name>Melissa Raspberry</Name></User> // func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { usr := new(User) err := request.ReadEntity(&usr) if err == nil { id := request.PathParameter("id") u.db.Model(&users).Where("id = ?", id).Update("name", usr.Name).Update("city", usr.City).Update("age", usr.Age) response.WriteEntity(usr) } else { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) } } // PUT http://localhost:8080/users/1 // <User><Id>1</Id><Name>Melissa</Name></User> // func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { usr := new(User) err := request.ReadEntity(&usr) if err == nil { u.db.Create(&usr) response.WriteHeaderAndEntity(http.StatusCreated, usr) } else { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) } } // DELETE http://localhost:8080/users/1 // func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("id") u.db.Where("id = ?", id).Delete(&users) } func main() { wsContainer := restful.NewContainer() wsContainer.Router(restful.CurlyRouter{}) db, err := gorm.Open(dbDriver, dbUser+":"+dbPass+"@"+tcp+"/"+dbName) if err != nil { panic("failed to connect database") } else { log.Println("Connection Established") } defer db.Close() userDao := db.Debug().Table("t_user") u := UserResource{userDao} u.Register(wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
使用postman测试
以上是关于go练习:实现mysql+ORM+restful api的主要内容,如果未能解决你的问题,请参考以下文章
十五Python 操作 MySQL 数据库------非ORM