Write a friendship link with Beego

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Beego Framework and Bee tool installation is very simple, the only thing to note is the Mac platform go1.8 version can not run Bee tool, said the official package caused by the bug, need to use a higher version, such as my Mac local version is:

zhgxun-pro:~ zhgxun$ go versiongo version go1.8.3 darwin/amd64

Now look at how to use the Beego framework to write a friendship link.

1. Create a table

CREATE TABLE `link` (  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,  `type` tinyint(1) NOT NULL DEFAULT 1 COMMENT '类型1官网2手册3其它',  `title` varchar(120) NOT NULL COMMENT '标题',  `url` varchar(255) NOT NULL COMMENT '地址',  `content` varchar(255) NOT NULL COMMENT '描述',  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态1可用2不可用',  `ctime` int(11) DEFAULT '0' COMMENT '创建时间',  `utime` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间',  PRIMARY KEY (`id`),  KEY `type`(`type`),  KEY `title`(`title`),  KEY `status`(`status`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='友情链接';

2. Write the Model

Links Package Modelsimport ("Time" "github.com/astaxie/beego/orm") type link struct {Id int64 type I NT Title string Url string Content string Status int Ctime Int64 utime int64}//linkstatus Friendship Link state func linkstatus () map[int]string {return map[int]string{1: "Available", 2: "Unavailable",}}//Linkstatusdesc Friends Emotion Link Status Description func linkstatusdesc (id int) string {if desc, OK: = Linkstatus () [id]; OK {return desc} return "Unknown        "}//linktypelist type func linktypelist () map[int]string {return map[int]string{1:" Official website ", 2:" Manual ", 3: "Other",}}//linktypedesc type description func linktypedesc (id int) string {if desc, OK: = Linktypelist () [id]; OK {RET Urn desc} return "Unknown"}//linksave Add link func linksave (l *link) (int64, error) {o: = orm. Neworm () L.status = 1 L.ctime = time. Now (). Unix () L.utime = time. Now (). Unix () return O.insert (L)}//linkupdate Update link func linkupdate (l *link) (Int64, error){o: = orm. Neworm () L.utime = time. Now (). Unix () If _, Err: = O.update (L);     Err! = Nil {return l.id, err} return l.id, nil}//linklist Friendship link list func linklist () []*link {var link link var links []*link o: = orm. Neworm () o.querytable (link). Relatedsel (). Filter ("Status", 1). All (&links) return links}//linkinfo Links details func linkinfo (ID Int64) (link, error) {var l link o: = orm. Neworm () Err: = O.querytable (L). Relatedsel (). Filter ("id", id). One (&l) return L, err}

3. Registration model

package mainimport (    _ "github.com/go-sql-driver/mysql"    "github.com/astaxie/beego"    "github.com/astaxie/beego/orm"    "step/models"    _ "step/routers")func init() {    orm.RegisterDataBase("default", "mysql", "root:@/step")    orm.RegisterModel(        new(models.Link),    )}func main() {    beego.Run()}

4. Registered Routing

package routersimport (    "github.com/astaxie/beego"    "step/controllers")func init() {    // 友情链接    beego.Router("/link", &controllers.LinkController{}, "GET:Index")    beego.Router("/link/create", &controllers.LinkController{}, "GET,POST:Create")    beego.Router("/link/:id([0-9]+)", &controllers.LinkController{}, "GET,POST:View")    beego.Router("/link/update/:id([0-9]+)", &controllers.LinkController{}, "GET,POST:Update")    beego.Router("/link/delete/:id([0-9]+)", &controllers.LinkController{}, "GET:Delete")}

5. Controller

Friendly link Package controllersimport ("FMT" "StrConv" "Strings" "Github.com/astaxie/beego" "step/models") type Linkcontroller struct {Beego. controller}//Index link list func (L *linkcontroller) index () {l.data["links"] = models. Linklist () l.data["types"] = models. Linktypelist () l.data["status"] = models. Linkstatus () l.layout = "base.html" l.tplname = "link/index.html"}//create Add link func (l *linkcontroller) create () {if L.ctx.request.method = = "POST" {typeId, err: = StrConv. Atoi (Strings. Trimspace (L.input (). Get ("type"))) if err! = Nil {l.redirect ("/link/create", 302)} title: = L.input (). Get ("title") URL: = L.input (). Get ("url") Content: = L.input (). Get ("content") if TypeId <= 0 {l.redirect ("/link/create", 302)} if strings. Trimspace (title) = = "" {L.redirect ("/link/create", 302)} if strings. Trimspace (URL) = = "" {L.redirect ("/liNk/create ", 302)} if strings. Trimspace (content) = = "" {L.redirect ("/link/create", 302)} var ID int64 if ID, err = MoD Els. Linksave (&models.        link{Type:typeid, Title:title, Url:url, Content:content, }); Err! = Nil {l.redirect ("/link/create", 302)} l.redirect ("/link/" +strconv. Formatint (ID, ten), 302)} l.data["Isnewrecord"] = True l.data["link"] = models. link{} l.data["types"] = models.     Linktypelist () l.layout = "base.html" l.tplname = "link/create.html"}//View link details func (l *linkcontroller) View () { ID, err: = StrConv. Atoi (L.ctx.input.param (": id")) if err! = Nil | | ID <= 0 {l.redirect ("/link", 302)} link, err: = models. LinkInfo (Int64 (ID)) If err! = Nil {l.redirect ("/link", 302)} l.data["link"] = link l.data["type"] = Models. Linktypedesc (link. Type) l.data["status"] = models. LinkstatuSdesc (link. Status) l.layout = "base.html" l.tplname = "link/view.html"}//update Edit link func (l *linkcontroller) update () {i D, err: = StrConv. Atoi (L.ctx.input.param (": id")) if err! = Nil | | ID <= 0 {l.redirect ("/link", 302)} link, err: = models.        LinkInfo (Int64 (ID)) If err! = Nil {l.redirect ("/link", 302)} if L.ctx.request.method = = "POST" { TypeId, err: = StrConv. Atoi (Strings. Trimspace (L.input (). Get ("type"))) if err! = Nil {l.redirect ("/link/update/" +strconv. Formatint (Int64 (ID), ten), 302)} link. Type = TypeId link. Title = strings. Trimspace (L.input (). Get ("title")) Link. URL = strings. Trimspace (L.input (). Get ("url")) Link. Content = strings. Trimspace (L.input (). Get ("content")) var newId int64 if newId, err = models. Linkupdate (&link); Err! = Nil {l.redirect ("/link/update/" +strconv. Formatint (NewId, ten), 302)} l.redirect ("/link/" +strconv. FOrmatint (NewId, ten), 302)} l.data["Isnewrecord"] = False l.data["link"] = link l.data["types"] = MODELS.L Inktypelist () l.layout = "base.html" l.tplname = "link/update.html"}//Delete Remove link func (l *linkcontroller) Delete ( {ID, err: = StrConv. Atoi (L.ctx.input.param (": id")) if err! = Nil | | ID <= 0 {l.redirect ("/link", 302)} link, err: = models. LinkInfo (Int64 (ID)) If err! = Nil {l.redirect ("/link", 302)} link. Status = 2 If _, err: = models. Linkupdate (&link); Err! = Nil {fmt. PRINTLN (Err)} l.redirect ("/link", 302)}

6. Templates

6.1 List index.html

<ol class= "breadcrumb" > <li><a href= "#" > Home </a></li> <li><a href= "#" > Content Management & lt;/a></li> <li class= "Active" > Links </li></ol><p> <a class= "btn btn-primary" href = "/link/create" > Add </a></p><p class= "Text-info" > Total search to <a class= "Text-success" >{{.links | Len}}</a> records that match the criteria. </p><table class= "Table table-bordered table-striped" > <thead> <tr> <th wi            Dth= "10%" >ID</th> <th width= "10%" > Type </th> <th width= "20%" > Name </th> <th width= "35%" > Description </th> <th width= "10%" > Status </th> <th width= "15%"            > Operations </th> </tr> </thead> <tbody> {{range. Links}} <tr> <td>{{. Id}}</td> <td>{{index $.types. Type}}</td> <td>{{. Title}}</td>            <td>{{. Content}}</td> <td>{{index $.status. status}}</td> <td> <a href= "/link/{{. ID}} "> View </a>&nbsp;&nbsp;| <a href="/link/update/{{. ID}} "> Edit </a>&nbsp;&nbsp;| <a href=" javascript:if (Confirm (' OK delete? ')] location.href= '/lin k/delete/{{. Id}} ' > Delete </a> </td> </tr> {{end}} </tbody></table>

6.2 Adding create.html

<ol class="breadcrumb">    <li><a href="#">首页</a></li>    <li><a href="#">内容管理</a></li>    <li><a href="/link">友情链接</a></li>    <li class="active">添加</li></ol>{{template "link/from.html" .}}

6.3 Form From.html

<form method= "POST" action= "/link/{{if. Isnewrecord}}create{{else}}update/{{.link. Id}}{{end}} "> <div class=" Form-group "> <label for=" type "> Type </label> <select class = "Form-control" id= "type" name= "type" > {{range $index, $type: =. Types}} <option id= "type_{{$i Ndex}} "Value=" {{$index}} ">{{$type}}</option> {{end}} </select> </div> <d IV class= "Form-group" > <label for= "title" > title </label> <input type= "text" class= "Form-contro L "id=" title "Name=" title "Value=" {{. link. Title}} "placeholder=" Please enter the caption "> </div> <div class=" Form-group "> <label for=" url "> Address </la bel> <input type= "text" class= "Form-control" id= "url" name= "url" value= "{{. link. URL}} "placeholder=" Please enter the title "> </div> <div class=" Form-group "> <label for=" Content "> Description </ label> <textarea class= "Form-controL "id=" content "name=" content "cols=" rows= "4" >{{.link. content}}</textarea> </div> <div class= "Form-group" > <button type= "Submit" class= "Btn BT N-primary ">{{if. Isnewrecord}} Add {{else}} edit {{end}}</button> </div></form><script type=" Text/javascript "> $ (Function () {$ (" #type_ {. link.    Type}} "). attr (" Selected "," Selected "); });</script>

6.4 Edit update.html

<ol class="breadcrumb">    <li><a href="#">首页</a></li>    <li><a href="#">内容管理</a></li>    <li><a href="/link">友情链接</a></li>    <li class="active">编辑</li></ol>{{template "link/from.html" .}}

6.5 Views View.html

<ol class= "breadcrumb" > <li><a href= "#" > Home </a></li> <li><a href= "#" > Content Management & lt;/a></li> <li><a href= "/link" > Links </a></li> <li class= "Active" > Details </li&  gt;</ol><p> <a class= "btn btn-primary" href= "/link/create" > Add </a> <a class= "Btn btn-info" Href= "/link/update/{{.link. ID}} "> Modify </a> <a class=" btn btn-danger "href="/link/delete/{{.link.         ID}} "> Delete </a></p><table class=" table table-bordered table-responsive "> <thead> <tr>    <th width= "10%" > Properties </th> <th width= "90%" > name </th> </tr> </thead> <tbody> <tr> <td>Id</td> <td>{{.link. id}}</td> </tr> <tr> <td> types </td> <td>{{.type}}</td> </ tr> <tr> <td> name </td> <td>{{.link. Title}}</td> </tr> <tr> <td> description </td> <td>{{.link.    Content}}</td> </tr> <tr> <td> status </td> <td>{{.status}}</td> </tr> </tbody></table>

7. Effect display
List

Add to

Modify

Details

8. Description

In the "Go Language Programming" book, section 7.7 mentions:

"The Go language does not currently have an authoritative web framework, just like the Ruby language has rails and Python has Django. This is not to say that such frameworks do not exist, but that the building blocks in the Go Language standard library are so flexible that they are unnecessary. In addition, although it is very convenient to use frameworks early in a project, they bring additional complexity that makes long-term maintenance more difficult. "

Compared to using PHP's mature Web development framework such as YII2, it does seem clumsy. Of course, you can do more packaging, do not do this here, just experience the use of go to write a simple link, you will know the general function of the implementation, there is a perfect framework is how convenient and beautiful. There is no attempt to generate code with BEE's auto-generation tool, but at least it should look smarter than the code above.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.