beego07----web博客
生活随笔
收集整理的這篇文章主要介紹了
beego07----web博客
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
conf/app.conf
appname = blog1 httpport = 8080 runmode = dev name=admin pwd=admincontrollersmy/attach.go
package controllersmyimport ("github.com/astaxie/beego" //導入beego包"io""net/url""os" )type AttachmentController struct {beego.Controller }func (c *AttachmentController) Get() {filePath, err := url.QueryUnescape(c.Ctx.Request.RequestURI[1:]) //去除最開頭的一個/if err != nil {c.Ctx.WriteString(err.Error())return}f, err := os.Open(filePath)if err != nil {c.Ctx.WriteString(err.Error())return}defer f.Close()_, err = io.Copy(c.Ctx.ResponseWriter, f) //2個參數是輸出流和輸入流if err != nil {c.Ctx.WriteString(err.Error())return} }controllersmy/default.go
//model的上層,下層調用models來操作數據庫package controllersmy //跟外面的包名一致import ("github.com/astaxie/beego" //導入beego包 )type MainController struct {beego.Controller //"github.com/astaxie/beego"包里面的Controller }func (c *MainController) Get() {c.TplName = "index.html" //返回頁面名字c.Data["isHome"] = truec.Data["isCookie"] = checkCookie(c.Ctx) }controllersmy/login.go
package controllersmyimport (//"fmt""github.com/astaxie/beego" //導入beego包"github.com/astaxie/beego/context"//"net/url" )type LoginController struct {beego.Controller }func (c *LoginController) Get() {c.Data["islogin"] = trueisExit := c.Input().Get("exit") == "true"if isExit {c.Ctx.SetCookie("name", "", -1, "/") //-1就會刪除cookiec.Ctx.SetCookie("pwd", "", -1, "/")return //不需要指定跳的首頁了 }c.TplName = "login.html" //返回頁面名字 }func (c *LoginController) Post() {//c.TplName = "login.html" //返回頁面名字c.Data["islogin"] = true//c.Ctx.WriteString(fmt.Sprint(c.Input())) //獲取post時候帶過來的參數,WriteString頁面就跳轉了不執行下面的了,uname := c.Input().Get("username")pwd := c.Input().Get("pwd")autologin := c.Input().Get("auto") == "on" //bool值//跟app.conf里面的用戶名和密碼比對if beego.AppConfig.String("name") == uname && beego.AppConfig.String("pwd") == pwd {maxAge := 0if autologin { //自動登陸就要設置cookiemaxAge = 1<<31 - 1}c.Ctx.SetCookie("name", uname, maxAge, "/") //保存時間和保存路徑c.Ctx.SetCookie("pwd", uname, maxAge, "/") //保存時間和保存路徑c.Redirect("/welcome", 301) //登陸后重定向到歡迎頁面//c.TplName = "welcome.html" //返回頁面名字,沒有走過濾器controller,Redirect走了過濾器controller,} else {return}return }//整個包可訪問 func checkCookie(ctx *context.Context) bool {ck, err := ctx.Request.Cookie("name") //獲取請求帶來的cookieif err != nil {return false}uname := ck.Valueck, err = ctx.Request.Cookie("pwd") //獲取請求帶來的cookieif err != nil {return false}pwd := ck.Valuereturn beego.AppConfig.String("name") == uname && beego.AppConfig.String("pwd") == pwd }controllersmy/topic.go
package controllersmyimport ("blog1/models""github.com/astaxie/beego" //導入beego包"path" )type TopicController struct {beego.Controller }func (c *TopicController) Get() {c.TplName = "topic.html" //返回頁面名字c.Data["isTopic"] = truec.Data["isCookie"] = checkCookie(c.Ctx) }func (c *TopicController) Post() {if !checkAccount(c.Ctx) { //沒有賬號登陸頁面c.Redirect("/login", 302)return}title := c.Input().Get("title")content := c.Input().Get("content")//獲取附件,上傳刪除修改跟cmss一樣,_, fh, err = this.GetFile("attachment")if err != nil {beego.Error(err)}var attachFilename stringif fh != nil {//保存附件attachFilename = fh.FileNamebeego.Info(attachFilename)//filement:tmp.go//path:attachments/tmp.goerr = this.SaveToFile("attachment", path.Join("attachments", attachFilename)) //path的第一個參數是工程目錄下attachments文件夾名字 }if len(id) == 0 {err := models.AddTopic(title, content, attachFilename)} else {err := models.ModifyTopic(id, title, content, attachFilename)}if err != nil {beego.Debug(err)}c.Redirect("/topic/view"+id, 302) //添加完之后跳轉到查看頁面 }func (c *TopicController) Add() {c.TplName = "topic_add.html" //返回頁面名字c.Ctx.WriteString("topic_add") }func (c *TopicController) View() { //查看單偏文章c.TplName = "topic_add.html"topic, err := models.GetOneTopic(c.Ctx.Input.Params("0")) //localhost:8080/topic/view/2343, Params("0")是2343if err != nil {c.Redirect("/", 302)}c.Data["Topic"] = topic//如果要獲取文章的回復,就到這個寫reply, err := models.GetAllApply(c.Ctx.Input.Params("0")) //localhost:8080/topic/view/2343, Params("0")是2343if err != nil {c.Redirect("/", 302)}c.Data["reply"] = reply }func (c *TopicController) Modify() { //查看單偏文章tid := c.Input().Get("id") //獲取url中傳過來的id topic, err := models.GetOneTopic(tid) //localhost:8080/topic/view/2343, Params("0")是2343if err != nil {c.Redirect("/", 302)return}c.Data["Topic"] = topicc.Data["id"] = idc.Redirect("/", 302) }func (c *TopicController) Delete() {if !checkAccount(c.Ctx) { //沒有賬號登陸頁面c.Redirect("/login", 302)return}err := models.DeleteTopic(c.Ctx.Input.Params("0"))if err != nil {beego.Error(err)}c.TplName = "topic_add.html" }controllersmy/welcome.go
package controllersmy //跟外面的包名一致import ("blog1/models"//"fmt""github.com/astaxie/beego" //導入beego包 )type WelcomeController struct {beego.Controller //"github.com/astaxie/beego"包里面的Controller }func (c *WelcomeController) Get() {op := c.Input().Get("op")beego.Debug("aaa")switch op {case "add"://c.Ctx.WriteString(fmt.Sprint(c.Input()))name := c.Input().Get("name")if len(name) == 0 {break}err := models.AddCatory(name)if err != nil {beego.Debug(err)return}case "del":beego.Debug("333")//c.Ctx.WriteString(fmt.Sprint(c.Input()))id := c.Input().Get("id")if len(id) == 0 {break}err := models.DelCatory(id)if err != nil {beego.Debug(err)}}c.Data["welcome"] = truevar err errorc.Data["Categories"], err = models.GetAllCategory(false)beego.Debug("111")beego.Debug(c.Data["Categories"])if err != nil {beego.Debug(err)}c.TplName = "welcome.html" //返回頁面名字,控制器之后寫頁面的名字, }model/models.go
//操作數據庫層,control調用,//使用beego的orm,先要創建好結構,然后將結構提交給orm進行創建表 package modelsimport ("github.com/Unknwon/com""github.com/astaxie/beego""github.com/astaxie/beego/orm" //導入beegoorm的路徑,_ "github.com/mattn/go-sqlite3" //go-sqlite3的驅動程序,_表示只執行初始化函數,"os""path""strconv""strings""time" )const (_DB_NAME = "data/beego1.db"_SQLITE3_DRIVER = "sqlite3" )//后面再添加字段,也可以動態在表中增加 type Category struct {Id int64 //名稱是Id,類型是int32或者int64,orm就認為是主鍵Title string //不指定長度,默認是255字節Created time.Time `orm:"index"` //創建時間,`orm:"index"`是tag,表示建立索引,Views int64 `orm:"index"` //瀏覽次數TopicTime time.Time `orm:"index"`newziduan string }// //打印 // beego.Trace("trace") // beego.Info("info") // beego.Debug("debug") // beego.Warn("warn") // beego.Error("error") type Topic struct {Id int64Uid int64Title stringContent string `orm:"size(5000)"`Attachment stringCreated time.Time `orm:"index"` //創建時間,`orm:"index"`是tag,Updated time.Time `orm:"index"` //創建時間,`orm:"index"`是tag,Views int64 `orm:"index"` //瀏覽次數 Author stringReplayTime time.Time `orm:"index"` }func RegisterDB() {if !com.IsExist(_DB_NAME) { //數據文件不存在就人為創建 os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)os.Create(_DB_NAME)}//orm需要先注冊模型Category、Topicorm.RegisterModel(new(Category), new(Topic))//注冊驅動 orm.RegisterDriver(_SQLITE3_DRIVER, orm.DRSqlite)//注冊默認數據庫,可以是多個數據庫,不管有幾個數據庫,默認數據庫名字要叫default//驅動名稱,數據庫路徑,最大連接數orm.RegisterDataBase("default", _SQLITE3_DRIVER, _DB_NAME, 10) }func AddCatory(name string) error {beego.Debug("aaa1")o := orm.NewOrm() //獲取orm對象o.Using("default")c := &Category{Title: name, Created: time.Now(), Views: 11, TopicTime: time.Now()} //創建Category對象,title=傳進來的name qs := o.QueryTable("category") //查詢判斷name是否被用了,使用的是beego的查詢,Category是表名,err := qs.Filter("title", name).One(c) //根據title找到category,One(c)預期只有一個, beego.Debug(err)if err == nil { //==nil表示找到了 beego.Debug(err)return err}beego.Debug("aaa")//否則插入id, err1 := o.Insert(c)beego.Debug("cc")if err1 != nil { //err != nil表示插入失敗 beego.Debug(err1)return err1}beego.Debug(id)beego.Debug("bbb")return nil }func GetAllCategory(isPaixu bool) ([]*Category, error) { //返回元素類型為Category的slice和erroro := orm.NewOrm()o.Using("default")cs := make([]*Category, 0) //定義一個sliceqs := o.QueryTable("category")var err errorif isPaixu {_, err = qs.All(&cs)} else {_, err = qs.OrderBy("-created").All(&cs) //根據created降序 }return cs, err }func DelCatory(id string) error {cid, err := strconv.ParseInt(id, 10, 64) //10進制,64位大小if err != nil {return err //人為非法操作 }o := orm.NewOrm()cat := &Category{Id: cid} //刪除必須要指定主鍵,如果不知道主鍵就要QueryTable,Filter操作_, err = o.Delete(cat) //前面下橫線表示不得到,否則你不使用就會報錯return err }func AddTopic(name, con label, attachment string) error {//空格作為多個標簽的分割,strings.Split(label, " ")通過空格把string分割成slice,//strings.Join將slice組合成string,label:="$"+strings.Join(strings.Split(label, " "), "#$") + "#"o := orm.NewOrm() //獲取orm對象o.Using("default")topic := &Topic{Title: name,Created: time.Now(),Views: 11,}topic.Title := strings.Replace(strings.Replace(Topic.Label, "#", " ", -1),"$", "", -1)//先把#變成空格,然后去除$, _, err1 := o.Insert(topic)if err1 != nil { //err != nil表示插入失敗 beego.Debug(err1)return err1}return nil }func GetOneTopic(id string) (*Topic, error) {tidnum, err := strconv.ParseInt(id, 10, 64) //把10進制的轉成64位if err != nil {return nil, err}o := orm.NewOrm()topic := new(Topic)qs := o.QueryTable("topic")err = qs.Filter("id", tidnum).One(topic) //理論上只有一個,qs.Filter("id", tidnum).All(&topic)是獲取所有, err = qs.Filter("labels__contains", "$"+label+"#")//模糊查詢,包含查詢,if err != nil {return nil, err}topic.Views++ //瀏覽數加一_, err = o.Update(topic) //更新return topic, err }func ModifyTopic(id, title, content string) error {tidnum, err := strconv.ParseInt(id, 10, 64) //把10進制的轉成64位if err != nil {return err}o := orm.NewOrm()topic := &Topic{Id: tidnum}if o.Read(topic) == nil {topic.Title = titletopic.Content = contento.Update(topic)}return err }func DeleteTopic(id, title, content string) error {cid, err := strconv.ParseInt(id, 10, 64) //10進制,64位大小if err != nil {return err //人為非法操作 }o := orm.NewOrm()top := &Topic{Id: cid} //刪除必須要指定主鍵,如果不知道主鍵就要QueryTable,Filter操作//先創建Topic對象,然后根據這個對象進行刪除,_, err = o.Delete(top) //前面下橫線表示不得到,否則你不使用就會報錯return err }routers/router.go
package routersimport ("blog1/controllersmy""github.com/astaxie/beego""os" )func init() {beego.Router("/", &controllersmy.MainController{}) //"blog1/controllersmy"里面的 &controllersmybeego.Router("/login", &controllersmy.LoginController{}) //"blog1/controllersmy"里面的 &controllersmybeego.Router("/welcome", &controllersmy.WelcomeController{})beego.Router("/topic", &controllersmy.TopicController{})beego.Router("/topic/add", &controllersmy.TopicController{}, "post:Add") //是post請求,并且是add方法,beego.Router("/topic/delete", &controllersmy.TopicController{}, "get:delete")//創建附件目錄attachmentsos.Mkdir("attachments", os.ModePerm)//作為靜態文件將附件反饋出來beego.SetStaticPath("/attachments", "attachment")//不作為靜態文件,作為一個控制器來處理beego.Router("/attachment/:all", &controllersmy.AttachmentController{}) }views/index.html
{{template "header" .}} <title>首頁</title><style type="text/css"></style> </head><body> {{template "navbar" .}}<!-- get請求就用a標簽就可以了,post請求還要寫一個表單 --><form method="POST" action="/login">表單登陸<input name="username" id="uname"/><input name="pwd"/ id="pwd"><input name="auto"/><input type="submit" onclick="return checkInput();"><input type="button" onclick="return backHome();">回到首頁</input></form>{{if .isCookie}}有cokie了{{end}}<script src="/static/js/reload.min.js"></script><script type="text/javascript">function checkInput(){var name = document.getElementById("uname")if (name.value.length == 0) {alert("輸入賬號")return false//不提交表單 }var pwd = document.getElementById("pwd")if (pwd.value.length == 0) {alert("輸入賬號")return false//不提交表單 }return true//提交表單 }function backHome(){window.location.href = "/"return false//表單一直不提交 }</script> </body> </html>views/login.html
{{template "header" .}} <title>登陸成功</title><style type="text/css"></style> </head><body>{{template "navbar" .}} 登陸成功<script src="/static/js/reload.min.js"></script> </body>views/T.head.tpl
{{define "header"}}<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" href="" type="image/x-icon" /><!-- <link id="mobile-style" type="text/css" rel="stylesheet" href="/static/css/main.css"><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script><link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"><link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"><script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> --> {{end}}views/T.navbar.tpl
{{define "navbar"}} <!-- if .isHome是contrloller傳遞進來的值 --><div {{if .isHome}}class="active"{{end}} style="height:100px;width:400px;background-color:red;display:inline-block;">首頁</div><div {{if .islogin}}class="active"{{end}} style="height:100px;width:400px;background-color:blue;display:inline-block;">登陸</div><ul class="nav navber-nav">{{if .islogin}}<li>登陸成功</li>{{else}}<li>首頁</li>{{end}}</ul> {{end}}views/topic.html
{{template "header" .}} <title>topic</title><style type="text/css"></style> </head><body>{{template "navbar" .}} {{.Topic.Title}} {{.Topic.Content}} {{.Topic.Attachment}} {{$tid := .Topic.Id}} <!-- 這就是一個模版變量 --> {{$isLogin := .IsLogin}} <script src="/static/js/reload.min.js"></script>{{if $isLogin}} <!-- 模版變量使用 --><a href="/topic/modify?id={{.Tid}}&tid={{$tid}}">修改文章</a> <!-- 模版變量的使用 -->{{end}}<form method="POST" action="/topic"><input name="name" id="name"/><input name="op" id="op"/><input type="file" name="attachment">文章附件</input><input type="submit">添加文章</input></form> </body>views/welcome.html
{{template "header" .}} <title>huayin</title><style type="text/css"></style> </head><body> {{template "navbar" .}}歡迎你<script src="/static/js/reload.min.js"></script><tbody>{{range .Categories}}<th>{{.Id}}</th><th>{{.Title}}</th><th>{{.TopicTime}}</th><a href="/welcome?op=del&id={{.Id}}">刪除</a><br>{{end}}</tbody>><form method="Get" action="/welcome"><input name="name" id="name"/><input name="op" id="op"/><input type="submit">add添加del刪除</input></form> </body> </html>main.go
package mainimport ("blog1/models"_ "blog1/routers""github.com/astaxie/beego""github.com/astaxie/beego/orm" )func main() {orm.Debug = trueorm.RunSyncdb("default", false, true) //建表,建立的數據庫在data目錄下, beego.Run() }func init() { //初始化數據庫,使用navicat premiun查看數據庫 models.RegisterDB() }?
轉載于:https://www.cnblogs.com/yaowen/p/8182192.html
總結
以上是生活随笔為你收集整理的beego07----web博客的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java并发编程实践读书笔记(3)任务执
- 下一篇: 城市联动