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{
Idint `json:"id"`
Namestring `json:"name"`
Citystring `json:"city"`
Ageint `json:"age"`
}varusers []Uservar dbDriver = "mysql"
var dbUser = "****"
var dbPass = "***"
var dbName = "test"
var tcp = "tcp(localhost:3306)"type UserResourcestruct{
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)
}//GEThttp://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)
}
}//POSThttp://localhost:8080/users//1Melissa Raspberry//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())
}
}//PUThttp://localhost:8080/users/1//1Melissa//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())
}
}//DELETEhttp://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())
}