golang(3):beego CRUD demo (1)

简介: 本文的原文连接是: http://blog.csdn.net/freewebsys/article/details/46699343 转载请一定注明出处!1,beego 自带crud生成工具工具执行非常简单:bee generate scaffold post -fields="title:string,body:text"设置模块post,里面的file

本文的原文连接是: 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代码生成的比较完善,其他的只生成一个文件而已。

目录
相关文章
|
关系型数据库 MySQL Go
Golang 语言 Web 框架 beego v2 之读操作(上)
Golang 语言 Web 框架 beego v2 之读操作
77 0
|
存储 关系型数据库 MySQL
Golang 语言 Web 框架 beego v2 之写操作
Golang 语言 Web 框架 beego v2 之写操作
151 0
|
JSON 缓存 Go
Golang 语言 Web 框架 beego v2 之控制器方法和输入输出数据
Golang 语言 Web 框架 beego v2 之控制器方法和输入输出数据
112 0
|
缓存 机器人 Go
Golang 语言 beego 学习之安装和快速入门
Golang 语言 beego 学习之安装和快速入门
78 0
|
监控 Go
Golang 语言 beego v2 之路由设置
Golang 语言 beego v2 之路由设置
254 0
|
26天前
|
中间件 Go API
Go语言中几种流行的Web框架,如Beego、Gin和Echo,分析了它们的特点、性能及适用场景,并讨论了如何根据项目需求、性能要求、团队经验和社区支持等因素选择最合适的框架
本文概述了Go语言中几种流行的Web框架,如Beego、Gin和Echo,分析了它们的特点、性能及适用场景,并讨论了如何根据项目需求、性能要求、团队经验和社区支持等因素选择最合适的框架。
67 1
|
4月前
|
人工智能 Go
Golang 搭建 WebSocket 应用(二) - 基本群聊 demo
Golang 搭建 WebSocket 应用(二) - 基本群聊 demo
45 1
|
SQL Go
Golang 语言 Web 框架 beego v2 之读操作(下)
Golang 语言 Web 框架 beego v2 之读操作(下)
90 0
|
前端开发 算法 JavaScript
Golang 语言 Web 框架 beego v2 之模板(下)
Golang 语言 Web 框架 beego v2 之模板(下)
125 0
|
SQL 缓存 开发框架
Golang 语言 Web 框架 beego v2 之模板(上)
Golang 语言 Web 框架 beego v2 之模板
86 0