beego07----web博客


conf/app.conf

appname = blog1
httpport = 8080
runmode = dev
name=admin
pwd=admin

controllersmy/attach.go

package controllersmy

import (
    "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"] = true

    c.Data["isCookie"] = checkCookie(c.Ctx)
}

controllersmy/login.go

package controllersmy

import (
    //"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"] = true

    isExit := c.Input().Get("exit") == "true"
    if isExit {
        c.Ctx.SetCookie("name", "", -1, "/") //-1就會刪除cookie
        c.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 := 0
        if autologin { //自動登陸就要設置cookie
            maxAge = 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") //獲取請求帶來的cookie
    if err != nil {
        return false
    }
    uname := ck.Value

    ck, err = ctx.Request.Cookie("pwd") //獲取請求帶來的cookie
    if err != nil {
        return false
    }
    pwd := ck.Value

    return beego.AppConfig.String("name") == uname && beego.AppConfig.String("pwd") == pwd
}

controllersmy/topic.go

package controllersmy

import (
    "blog1/models"
    "github.com/astaxie/beego" //導入beego包
    "path"
)

type TopicController struct {
    beego.Controller
}

func (c *TopicController) Get() {
    c.TplName = "topic.html" //返回頁面名字
    c.Data["isTopic"] = true
    c.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 string
    if fh != nil {
        //保存附件
        attachFilename = fh.FileName
        beego.Info(attachFilename)
        //filement:tmp.go
        //path:attachments/tmp.go
        err = 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")是2343
    if 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")是2343
    if 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")是2343
    if err != nil {
        c.Redirect("/", 302)
        return
    }
    c.Data["Topic"] = topic
    c.Data["id"] = id

    c.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"] = true
    var err error
    c.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 models

import (
    "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         int64
    Uid        int64
    Title      string
    Content    string `orm:"size(5000)"`
    Attachment string
    Created    time.Time `orm:"index"` //創建時間,`orm:"index"`是tag,
    Updated    time.Time `orm:"index"` //創建時間,`orm:"index"`是tag,
    Views      int64     `orm:"index"` //瀏覽次數
    Author     string
    ReplayTime 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、Topic
    orm.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和error
    o := orm.NewOrm()
    o.Using("default")
    cs := make([]*Category, 0) //定義一個slice
    qs := o.QueryTable("category")
    var err error
    if 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 = title
        topic.Content = content
        o.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 routers

import (
    "blog1/controllersmy"
    "github.com/astaxie/beego"
    "os"
)

func init() {
    beego.Router("/", &controllersmy.MainController{})       //"blog1/controllersmy"里面的 &controllersmy
    beego.Router("/login", &controllersmy.LoginController{}) //"blog1/controllersmy"里面的 &controllersmy
    beego.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")

    //創建附件目錄attachments
    os.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 main

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

func main() {
    orm.Debug = true
    orm.RunSyncdb("default", false, true) //建表,建立的數據庫在data目錄下,
    beego.Run()
}

func init() { //初始化數據庫,使用navicat premiun查看數據庫
    models.RegisterDB()
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM