golang(3):beego CRUD demo (1)

freewebsys · · 2810 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

本文的原文连接是: http://blog.csdn.net/freewebsys/article/details/46699343 转载请一定注明出处!

1,beego 自带crud生成工具

工具执行非常简单:

bee generate scaffold post -fields="title:string,body:text"

设置模块post,里面的fileds有两个 title 和body。

bee generate scaffold post -fields="title:string,body:text"
2015/06/30 19:00:54 [INFO] Using 'post' as scaffold name
2015/06/30 19:00:54 [INFO] Do you want me to create a post model? [yes|no]]  yes
2015/06/30 19:00:56 [INFO] Using 'Post' as model name
2015/06/30 19:00:56 [INFO] Using 'models' as package name
2015/06/30 19:00:56 [INFO] model file generated: /Users/freewebsys/Workspace_go/demo1/src/models/post.go
2015/06/30 19:00:56 [INFO] Do you want me to create a post controller? [yes|no]]  yes
2015/06/30 19:00:58 [INFO] Using 'Post' as controller name
2015/06/30 19:00:58 [INFO] Using 'controllers' as package name
2015/06/30 19:00:58 [INFO] controller file generated: /Users/freewebsys/Workspace_go/demo1/src/controllers/post.go
2015/06/30 19:00:58 [INFO] Do you want me to create views for this post resource? [yes|no]]  yes
2015/06/30 19:01:01 [INFO] Created: /Users/freewebsys/Workspace_go/demo1/src/views/post/index.tpl
2015/06/30 19:01:01 [INFO] Created: /Users/freewebsys/Workspace_go/demo1/src/views/post/show.tpl
2015/06/30 19:01:01 [INFO] Created: /Users/freewebsys/Workspace_go/demo1/src/views/post/create.tpl
2015/06/30 19:01:01 [INFO] Created: /Users/freewebsys/Workspace_go/demo1/src/views/post/edit.tpl
2015/06/30 19:01:01 [INFO] Do you want me to create a post migration and schema for this resource? [yes|no]]  yes
2015/06/30 19:01:07 [INFO] Migration file generated: /Users/freewebsys/Workspace_go/demo1/src/database/migrations/20150630_190107_post.go
2015/06/30 19:01:07 [INFO] Do you want to go ahead and migrate the database? [yes|no]]  no
2015/06/30 19:01:09 [INFO] All done! Don't forget to add  beego.Router("/post" ,&controllers.PostController{}) to routers/route.go
2015/06/30 19:01:09 [SUCC] generate successfully created!

生成了一堆代码,但是controller的代码是空方法,生成的页面代也是只有一行。

models里面的代码很全:

package models

import (
    "errors"
    "fmt"
    "reflect"
    "strings"

    "github.com/astaxie/beego/orm"
)

type Post struct {
    Id    int64  `orm:"auto"`
    Title string `orm:"size(128)"`
    Body  string `orm:"type(longtext)"`
}

func init() {
    orm.RegisterModel(new(Post))
}

// AddPost insert a new Post into database and returns
// last inserted Id on success.
func AddPost(m *Post) (id int64, err error) {
    o := orm.NewOrm()
    id, err = o.Insert(m)
    return
}

// GetPostById retrieves Post by Id. Returns error if
// Id doesn't exist
func GetPostById(id int) (v *Post, err error) {
    o := orm.NewOrm()
    v = &Post{Id: id}
    if err = o.Read(v); err == nil {
        return v, nil
    }
    return nil, err
}

// GetAllPost retrieves all Post matches certain condition. Returns empty list if
// no records exist
func GetAllPost(query map[string]string, fields []string, sortby []string, order []string,
    offset int64, limit int64) (ml []interface{}, err error) {
    o := orm.NewOrm()
    qs := o.QueryTable(new(Post))
    // query k=v
    for k, v := range query {
        // rewrite dot-notation to Object__Attribute
        k = strings.Replace(k, ".", "__", -1)
        qs = qs.Filter(k, v)
    }
    // order by:
    var sortFields []string
    if len(sortby) != 0 {
        if len(sortby) == len(order) {
            // 1) for each sort field, there is an associated order
            for i, v := range sortby {
                orderby := ""
                if order[i] == "desc" {
                    orderby = "-" + v
                } else if order[i] == "asc" {
                    orderby = v
                } else {
                    return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
                }
                sortFields = append(sortFields, orderby)
            }
            qs = qs.OrderBy(sortFields...)
        } else if len(sortby) != len(order) && len(order) == 1 {
            // 2) there is exactly one order, all the sorted fields will be sorted by this order
            for _, v := range sortby {
                orderby := ""
                if order[0] == "desc" {
                    orderby = "-" + v
                } else if order[0] == "asc" {
                    orderby = v
                } else {
                    return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
                }
                sortFields = append(sortFields, orderby)
            }
        } else if len(sortby) != len(order) && len(order) != 1 {
            return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
        }
    } else {
        if len(order) != 0 {
            return nil, errors.New("Error: unused 'order' fields")
        }
    }

    var l []Post
    qs = qs.OrderBy(sortFields...)
    if _, err := qs.Limit(limit, offset).All(&l, fields...); err == nil {
        if len(fields) == 0 {
            for _, v := range l {
                ml = append(ml, v)
            }
        } else {
            // trim unused fields
            for _, v := range l {
                m := make(map[string]interface{})
                val := reflect.ValueOf(v)
                for _, fname := range fields {
                    m[fname] = val.FieldByName(fname).Interface()
                }
                ml = append(ml, m)
            }
        }
        return ml, nil
    }
    return nil, err
}

// UpdatePost updates Post by Id and returns error if
// the record to be updated doesn't exist
func UpdatePostById(m *Post) (err error) {
    o := orm.NewOrm()
    v := Post{Id: m.Id}
    // ascertain id exists in the database
    if err = o.Read(&v); err == nil {
        var num int64
        if num, err = o.Update(m); err == nil {
            fmt.Println("Number of records updated in database:", num)
        }
    }
    return
}

// DeletePost deletes Post by Id and returns error if
// the record to be deleted doesn't exist
func DeletePost(id int) (err error) {
    o := orm.NewOrm()
    v := Post{Id: id}
    // ascertain id exists in the database
    if err = o.Read(&v); err == nil {
        var num int64
        if num, err = o.Delete(&Post{Id: id}); err == nil {
            fmt.Println("Number of records deleted in database:", num)
        }
    }
    return
}

3,运行项目

要运行项目需要再src目录下面增加一个main.go

package main

import (
    _ "routers"
    "github.com/astaxie/beego"
)

func main() {
    beego.Run()
}

同时在,src/routers,下面增加router.go

package routers

import (
    "controllers"
    "github.com/astaxie/beego"
)

func init() {

    beego.Router("/post/list",&controllers.PostController{},"get:List")
    beego.Router("/post/edit",&controllers.PostController{},"get:Edit")
    beego.Router("/post/save",&controllers.PostController{},"post:Save")
    beego.Router("/post/delete",&controllers.PostController{},"delete:Delete")
}

由于controller没有自动生成,需要自己修改:

package controllers

import (
    "github.com/astaxie/beego"
)

// operations for Post
type PostController struct {
    beego.Controller
}

func (c *PostController) List() {
    c.TplNames = "post/list.tpl"
}


func (c *PostController) Edit() {
    c.TplNames = "post/edit.tpl"
}

func (c *PostController) Save() {
    c.Ctx.WriteString("hello")
    //c.TplNames = "post/index.tpl"
}

func (c *PostController) Delete() {
    c.Ctx.WriteString("hello")
    //c.TplNames = "post/index.tpl"
}

4,总结

本文的原文连接是: http://blog.csdn.net/freewebsys/article/details/46699343 转载请一定注明出处!

对beego的代码生成工具有了一个简单的了解,其中mvc中,module代码生成的比较完善,其他的只生成一个文件而已。


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:freewebsys

查看原文:golang(3):beego CRUD demo (1)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077

2810 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传