2

彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-模板与数据库EP02 - 刘...

 2 years ago
source link: https://www.cnblogs.com/v3ucn/p/16614612.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-模板与数据库EP02

书接上回,上次我们搭建好了项目入口文件,同时配置了路由体系,接着就可以配置项目的模板了,这里我们采用Iris内置的模板引擎,事实上,采用模板引擎并不意味着前后端耦合,模板中的数据保持其独立性即可,也就是说模板的数据操作交互方式采用http接口请求的形式,Iris并不参与模板逻辑,只返回Json格式的数据即可。前端集成数据双向绑定机制的框架Vue.js。

Iris支持但不限于下面几种模板引擎:

#	Name	Parser  
1	HTML	html/template  
2	Blocks	kataras/blocks  
3	Django	flosch/pongo2  
4	Pug	Joker/jade  
5	Handlebars	aymerick/raymond  
6	Amber	eknkc/amber  
7	Jet	CloudyKit/jet  
8	Ace	yosssi/ace

这里我们使用默认的引擎html/template,参见模板语法文档示例:https://github.com/kataras/iris/tree/master/_examples/view

编写main.go文件:

tmpl := iris.HTML("./views", ".html")

这里声明并赋值tmpl变量,传入模板文件夹以及模板文件后缀两个参数。

随后在项目根目录创建views文件夹:

mkdir views  
cd views

接着建立模板文件test.html:

<html>  
<head>  
    <title>首页</title>  
</head>  
<body>  
    <h1>${.message}</h1>  
</body>  
</html>

这是一个简单的测试模板,打印变量.message。

随后添加模板配置:

tmpl.Delims("${", "}")  
  
tmpl.Reload(true)  
  
app.RegisterView(tmpl)

这里添加模板的通配符,采用${},避免和Vue的打印模板语法{{}}冲突,然后开启修改后重新加载的模式,防止模板被缓存,最后注册模板。

最后,在路由函数内解析模板:

app.Get("/", func(ctx iris.Context) {  
		  
		ctx.ViewData("message", "你好,女神")  
	  
		ctx.View("test.html")  
	})

编译后访问http://localhost:5000

20220818130824_98754.png

这里通过ctx.ViewData函数将message变量传递给模板,然后渲染.message

这只是最简单的模板解析,我们还需要让Iris提供静态文件的服务支持,否则模板将无法加载样式文件或者是Js文件:

app.HandleDir("/assets", iris.Dir("./assets"))

这里将根目录的assets文件作为静态文件目录进行解析。

随后将项目的css文件和js文件放入assets对应目录,接着编写index.html首页模板:

<!DOCTYPE html>  
<html lang="zh-CN">  
  <head>  
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">  
    <meta http-equiv="X-UA-Compatible" content="IE=edge">  
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <meta name="applicable-device" content="pc,mobile" />  
  <title>刘悦-刘悦分享-刘悦的技术博客-讲师刘悦-刘悦简历</title>  
<meta content="刘悦的技术博客,刘悦简历,python编程,git,mac,centos,ruby编程,linux,golang编程,vue.js,Docker容器技术" name="keywords">  
<meta content="刘悦-刘悦分享-刘悦的技术博客-讲师刘悦-刘悦简历" name="description">  
<meta content="index,follow" name="robots">  
<meta content="index,follow" name="GOOGLEBOT">  
<meta content="刘悦"  name="Author">  
  
  <meta http-equiv="expires" content="4500"/>  
  
   <link rel="stylesheet" href="../assets/css/style.css"  />  
  
   <script src="../assets/js/axios.js"></script>  
    <script src="../assets/js/vue.js"></script>  
  
  
  </head>

这里通过link和script标签将需要的样式和Js标准库引入:分别是style.css、Vue.js和axios.js文件

随后,添加id标识:

<div id="app">

接着在body标签外侧添加Vue初始化逻辑:

<script>  
  
  
const App = {  
            data() {  
                return {  
                    message: "Hello Tornado",  
                };  
            },  
            created: function() {  
  
                console.log("你好,女神");  
  
            },  
            methods: {  
            },  
        };  
const app = Vue.createApp(App);  
app.config.globalProperties.axios = axios;  
app.mount("#app");  
  
  
  
</script>

这里当Iris模板渲染时,自动初始化Vue框架,前端交互留给Vue.js。

如果愿意,网站的icon也可以交给Iris渲染:

app.Favicon("./favicon.ico")

接着修改main.go逻辑,改为渲染首页模板:

app.Get("/", func(ctx iris.Context) {  
	  
		ctx.ViewData("message", "你好,女神")  
		  
		ctx.View("index.html")  
	})

访问http://localhost:5000:

20220818130844_68277.png

如此,Iris模板和静态服务就配置好了。

配置数据库

Iris项目需要将数据存储在数据库中,这里使用Gorm包,安装方式详见:百亿数据百亿花, 库若恒河沙复沙,Go lang1.18入门精炼教程,由白丁入鸿儒,Go lang数据库操作实践EP12

随后修改main.go文件:



db, err := gorm.Open("mysql", "root:root@(localhost)/irisblog?charset=utf8mb4&parseTime=True&loc=Local")  
  
	if err != nil {  
		fmt.Println(err)  
		panic("无法连接数据库")  
	}  
	fmt.Println("连接数据库成功")  
  
	//单数模式  
	db.SingularTable(true)  
  
	// 创建默认表  
	db.AutoMigrate(&model.User{})  
  
	// 逻辑结束后关闭数据库  
	defer func() {  
		_ = db.Close()  
	}()


这里通过mysql驱动连接数据库,注意默认启动会通过结构体创建用户表。

随后在根目录创建模型包:

mkdir model  
cd model

接着创建数据模型包:

package model  
  
import (  
	"time"  
	"github.com/jinzhu/gorm"  
)  
  
type Model struct {  
	ID        uint `gorm:"primary_key"`  
	CreatedAt time.Time  
	UpdatedAt time.Time  
	DeletedAt *time.Time  
}  
  
type User struct {  
	gorm.Model  
	Username string  
	Password string  
}

这里通过结构体的属性传递,可以让User结构体具备Gorm内置的Model结构体的字段,类似“继承”的方式。

最后,封装Iris结构体,将db变量传递进去:

package main  
  
import (  
	"IrisBlog/model"  
	"fmt"  
  
	"github.com/jinzhu/gorm"  
	_ "github.com/jinzhu/gorm/dialects/mysql"  
	"github.com/kataras/iris/v12"  
)  
  
func main() {  
  
	db, err := gorm.Open("mysql", "root:root@(localhost)/irisblog?charset=utf8mb4&parseTime=True&loc=Local")  
  
	if err != nil {  
		fmt.Println(err)  
		panic("无法连接数据库")  
	}  
	fmt.Println("连接数据库成功")  
  
	//单数模式  
	db.SingularTable(true)  
  
	// 创建默认表  
	db.AutoMigrate(&model.User{})  
  
	// 逻辑结束后关闭数据库  
	defer func() {  
		_ = db.Close()  
	}()  
  
	app := newApp(db)  
  
	app.HandleDir("/assets", iris.Dir("./assets"))  
	app.Favicon("./favicon.ico")  
	app.Listen(":5000")  
}  
  
func newApp(db *gorm.DB) *iris.Application {  
  
	app := iris.New()  
  
	tmpl := iris.HTML("./views", ".html")  
	// Set custom delimeters.  
	tmpl.Delims("${", "}")  
	// Enable re-build on local template files changes.  
	tmpl.Reload(true)  
  
	app.RegisterView(tmpl)  
  
	app.Get("/", func(ctx iris.Context) {  
  
		ctx.ViewData("message", "你好,女神")  
  
		ctx.View("index.html")  
	})  
  
	return app  
  
}

如此,数据库就配置好了,当前的项目结构如下:

IrisBlog  
├── assets  
│ ├── css  
│ │ └── style.css  
│ └── js  
│     ├── axios.js  
│     └── vue.js  
├── favicon.ico  
├── go.mod  
├── go.sum  
├── main.go  
├── model  
│ └── model.go  
├── tmp  
│ └── runner-build  
└── views  
    ├── index.html  
    └── test.html

本次我们完成了项目模板和数据库的配置,并且在战略层面重新规划了项目结构,正道是:雄关漫道真如铁,而今迈步从头越,该项目已开源在Github:https://github.com/zcxey2911/IrisBlog ,与君共觞,和君共勉。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK