1
0
mirror of https://github.com/beego/bee.git synced 2024-11-21 18:40:54 +00:00

an example for api application

This commit is contained in:
miraclesu 2013-07-09 15:16:28 +08:00
parent 6bfd839b68
commit b4b8225cbf

145
apiapp.go
View File

@ -24,7 +24,7 @@ In the appname folder has the follow struct:
   default.go    default.go
main.go main.go
models models
default.go object.go
`, `,
} }
@ -34,109 +34,142 @@ appname = {{.Appname}}
httpport = 8080 httpport = 8080
runmode = dev runmode = dev
autorender = false autorender = false
copyrequestbody = true
` `
var apiMaingo = `package main var apiMaingo = `package main
import ( import (
"{{.Appname}}/controllers"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"{{.Appname}}/controllers"
) )
// Objects
// URL HTTP Verb Functionality
// /object POST Creating Objects
// /object/<objectId> GET Retrieving Objects
// /object/<objectId> PUT Updating Objects
// /object GET Queries
// /object/<objectId> DELETE Deleting Objects
func main() { func main() {
beego.Router("/{{.Version}}/users/:objectId", &controllers.UserController{}) beego.RESTRouter("/object", &controllers.ObejctController{})
beego.Router("/{{.Version}}/users", &controllers.UserController{})
beego.Run() beego.Run()
} }
` `
var apiModels = `package models var apiModels = `package models
type User struct { import (
Id interface{} "errors"
Name string "strconv"
Email string "time"
)
var (
Objects map[string]*Object
)
type Object struct {
ObjectId string
Score int64
PlayerName string
} }
func (this *User) One(id interface{}) (user User, err error) { func init() {
// get user from DB Objects = make(map[string]*Object)
// user, err = query(id) Objects["hjkhsbnmn123"] = &Object{"hjkhsbnmn123", 100, "astaxie"}
user = User{id, "astaxie", "astaxie@gmail.com"} Objects["mjjkxsxsaa23"] = &Object{"mjjkxsxsaa23", 101, "someone"}
return
} }
func (this *User) All() (users []User, err error) { func AddOne(object Object) (ObjectId string) {
// get all users from DB object.ObjectId = "astaxie" + strconv.FormatInt(time.Now().UnixNano(), 10)
// users, err = queryAll() Objects[object.ObjectId] = &object
users = append([]User{}, User{1, "astaxie", "astaxie@gmail.com"}) return object.ObjectId
users = append(users, User{2, "someone", "someone@gmail.com"})
return
} }
func (this *User) Update(id interface{}) (err error) { func GetOne(ObjectId string) (object *Object, err error) {
// user, err = update(id, this) if v, ok := Objects[ObjectId]; ok {
return return v, nil
}
return nil, errors.New("ObjectId Not Exist")
} }
func GetAll() map[string]*Object {
return Objects
}
func Update(ObjectId string, Score int64) (err error) {
if v, ok := Objects[ObjectId]; ok {
v.Score = Score
return nil
}
return errors.New("ObjectId Not Exist")
}
func Delete(ObjectId string) {
delete(Objects, ObjectId)
}
` `
var apiControllers = `package controllers var apiControllers = `package controllers
import ( import (
"encoding/json" "encoding/json"
"{{.Appname}}/models"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"io/ioutil" "{{.Appname}}/models"
) )
type UserController struct { type ResponseInfo struct {
}
type ObejctController struct {
beego.Controller beego.Controller
} }
func (this *UserController) Get() { func (this *ObejctController) Post() {
var user models.User var ob models.Object
json.Unmarshal(this.Ctx.RequestBody, &ob)
objectid := models.AddOne(ob)
this.Data["json"] = "{\"ObjectId\":\"" + objectid + "\"}"
this.ServeJson()
}
func (this *ObejctController) Get() {
objectId := this.Ctx.Params[":objectId"] objectId := this.Ctx.Params[":objectId"]
if objectId != "" { if objectId != "" {
user, err := user.One(objectId) ob, err := models.GetOne(objectId)
if err != nil { if err != nil {
this.Data["json"] = err this.Data["json"] = err
} else { } else {
this.Data["json"] = user this.Data["json"] = ob
} }
} else { } else {
users, err := user.All() obs := models.GetAll()
if err != nil { this.Data["json"] = obs
this.Data["json"] = err
} else {
this.Data["json"] = users
}
} }
this.ServeJson() this.ServeJson()
} }
func (this *UserController) Put() { func (this *ObejctController) Put() {
defer this.ServeJson()
var user models.User
objectId := this.Ctx.Params[":objectId"] objectId := this.Ctx.Params[":objectId"]
var ob models.Object
json.Unmarshal(this.Ctx.RequestBody, &ob)
body, err := ioutil.ReadAll(this.Ctx.Request.Body) err := models.Update(objectId, ob.Score)
if err != nil {
this.Data["json"] = err
return
}
this.Ctx.Request.Body.Close()
if err = json.Unmarshal(body, &user); err != nil {
this.Data["json"] = err
return
}
err = user.Update(objectId)
if err != nil { if err != nil {
this.Data["json"] = err this.Data["json"] = err
} else { } else {
this.Data["json"] = "update success!" this.Data["json"] = "update success!"
} }
this.ServeJson()
} }
func (this *ObejctController) Delete() {
objectId := this.Ctx.Params[":objectId"]
models.Delete(objectId)
this.Data["json"] = "delete success!"
this.ServeJson()
}
` `
func init() { func init() {
@ -144,10 +177,7 @@ func init() {
} }
func createapi(cmd *Command, args []string) { func createapi(cmd *Command, args []string) {
version := "1" if len(args) != 1 {
if len(args) == 2 {
version = args[1]
} else if len(args) != 1 {
fmt.Println("error args") fmt.Println("error args")
os.Exit(2) os.Exit(2)
} }
@ -173,11 +203,10 @@ func createapi(cmd *Command, args []string) {
writetofile(path.Join(apppath, "controllers", "default.go"), writetofile(path.Join(apppath, "controllers", "default.go"),
strings.Replace(apiControllers, "{{.Appname}}", packpath, -1)) strings.Replace(apiControllers, "{{.Appname}}", packpath, -1))
fmt.Println("create models default.go:", path.Join(apppath, "models", "default.go")) fmt.Println("create models object.go:", path.Join(apppath, "models", "object.go"))
writetofile(path.Join(apppath, "models", "default.go"), apiModels) writetofile(path.Join(apppath, "models", "object.go"), apiModels)
fmt.Println("create main.go:", path.Join(apppath, "main.go")) fmt.Println("create main.go:", path.Join(apppath, "main.go"))
apiMaingo = strings.Replace(apiMaingo, "{{.Version}}", version, -1)
writetofile(path.Join(apppath, "main.go"), writetofile(path.Join(apppath, "main.go"),
strings.Replace(apiMaingo, "{{.Appname}}", packpath, -1)) strings.Replace(apiMaingo, "{{.Appname}}", packpath, -1))
} }