用 go 實現一個簡單的 mvc

jcc123發表於2019-06-09

demo

github

從這個文件build-web-application-with-golang學習到很多。

下載

git clone https://github.com/jc91715/go-simple-mvc

安裝依賴

go get github.com/astaxie/beego
go get github.com/go-sql-driver/mysql

執行

go run main.go

訪問 localhost:9090

使用說明

1 新增路由

routes/web.go

a.AddRoute("/posts/:post_id([0-9]+)", map[string]string{
        "GET": "Show",//對應PostController的Show方法
    }, &controller.PostController{})

2 建立控制器

controller下建立PostController.go

package controller

//匯入要用到的包

type PostController struct {
    Controller
}
func (c *PostController) Show() {//新增方法

}

3 模型

使用的beego-orm

package model

type RainlabBlogPosts struct {
    Id          int
    Title       string
    ContentHtml string
}

使用

    o := orm.NewOrm()

    post := model.RainlabBlogPosts{Id: id}

4 檢視

view資料夾下

抽離出header.tplfooter.tpl

{{define "header"}}
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>go-simple-mvc</title>
    <style>
      body{
        margin:30px;

      }
    </style>
</head>
<body>
{{end}}
{{define "footer"}}
</body>
</html>
{{end}}

例子 post/show.tpl

{{define "show"}}
{{template "header"}}
<div style="text-align:center"> 
  <a href="/" >回首頁</a>
</div>
<div style="width:80%;margin-left:10%"> 
  {{.}}
</div>

{{template "footer"}}
{{end}}

控制器呼叫檢視

  s1, _ := template.ParseFiles("view/layout/header.tpl", "view/post/show.tpl", "view/layout/footer.tpl")//裝載檢視

  s1.ExecuteTemplate(c.Ct.ResponseWriter, "show", "string")

資料庫表結構結構

CREATE TABLE `rainlab_blog_posts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `content_html` longtext COLLATE utf8mb4_unicode_ci,
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

NOT IS BECAUSE I WANT TO WRITE,
BUT I WANT TO INCREASE,
SO I GO TO WRITE~~

相關文章