• 彩虹女神跃长空,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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

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

    编写main.go文件:

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

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

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

    mkdir views  
    cd views
    
    • 1
    • 2

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

      
      
        首页  
      
      
        

    ${.message}

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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

    随后添加模板配置:

    tmpl.Delims("${", "}")  
      
    tmpl.Reload(true)  
      
    app.RegisterView(tmpl)
    
    • 1
    • 2
    • 3
    • 4
    • 5

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

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

    app.Get("/", func(ctx iris.Context) {  
    		  
    		ctx.ViewData("message", "你好,女神")  
    	  
    		ctx.View("test.html")  
    	})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

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

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

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

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

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

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

      
      
        
          
          
          
          
      刘悦-刘悦分享-刘悦的技术博客-讲师刘悦-刘悦简历  
      
      
      
      
      
      
        
      
         
      
         
          
      
      
      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

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

    随后,添加id标识:

    • 1

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

    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

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

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

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

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

    app.Get("/", func(ctx iris.Context) {  
    	  
    		ctx.ViewData("message", "你好,女神")  
    		  
    		ctx.View("index.html")  
    	})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    访问http://localhost:5000:

    如此,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()  
    	}()
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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

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

    mkdir model  
    cd model
    
    • 1
    • 2

    接着创建数据模型包:

    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  
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    这里通过结构体的属性传递,可以让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  
      
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

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

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    结语

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

  • 相关阅读:
    Linux进程控制
    企业运维 | MySQL关系型数据库在Docker与Kubernetes容器环境中快速搭建部署主从实践
    JVM之class文件结构剖析
    【杂记-浅谈Time To Live/TTL】
    编写一个函数,输入一个十进制数,输出对应 的十六进制数。(不能用printf的%x格式说明符)
    多显示屏,将Qt程序显示在指定显示器上
    C/C++数据结构之中缀表达式转换为后缀表达式,删除堆栈元素
    Qt之显示PDF文件
    微软:Octo Tempest是最危险的金融黑客组织之一
    响应的结构与Http常见状态码
  • 原文地址:https://blog.csdn.net/zcxey2911/article/details/126475468