GoFrame 資源管理-使用示例

2022-04-07 10:49 更新

我們來看一個使用示例,在該示例中,展示了資源管理在?WebServer?的靜態(tài)服務(wù)、配置管理、模板引擎中的使用。

資源文件

資源文件源碼:https://github.com/gogf/gf/v2/tree/master/os/gres/testdata/example/files

資源文件打包:https://github.com/gogf/gf/v2/tree/master/os/gres/testdata/example/boot

資源文件列表:

2020-03-28T13:04:10+00:00   0.00B config
2020-03-28T13:03:06+00:00 135.00B config/config.toml
2020-03-28T13:04:10+00:00   0.00B public
2020-03-28T12:57:54+00:00   6.00B public/index.html
2020-03-28T13:04:10+00:00   0.00B template
2020-03-28T13:03:17+00:00  15.00B template/index.tpl
TOTAL FILES: 6

三個文件的內(nèi)容分別為:

  • ?config.toml?

該文件為應(yīng)用的配置文件。

 [server]
     Address    = ":8888"
     ServerRoot = "public"

 [viewer]
     DefaultFile = "index.tpl"
     Delimiters  = ["${", "}"]
  • ?index.html?

該文件用于靜態(tài)資源請求。

 Hello!
  • ?index.tpl?

該文件用于模板文件解析展示。

 Hello ${.name}!

創(chuàng)建應(yīng)用

package main

import (
	_ "github.com/gogf/gf/v2/os/gres/testdata/example/boot"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

func main() {
	s := g.Server()
	s.Group("/", func(group *ghttp.RouterGroup) {
		group.GET("/template", func(r *ghttp.Request) {
			r.Response.WriteTplDefault(g.Map{
				"name": "GoFrame",
			})
		})
	})
	s.Run()
}

可以看到,整個代碼中除了?import?中額外增加了一個 ?_ "github.com/gogf/gf/v2/os/gres/testdata/example/boot"? 的包引入外,沒有其他任何設(shè)置。這也是?GoFrame?框架的資源管理比較便捷的地方,資源管理并不需要開發(fā)階段對代碼做任何特殊設(shè)置,在應(yīng)用程序部署之前打包好資源文件,并通過?import?增加資源文件的引入即可。

運行后,終端輸出:

2020-03-28 21:36:19.828 75892: http server started listening on [:8888]

  SERVER  | DOMAIN  | ADDRESS | METHOD |   ROUTE   |      HANDLER      | MIDDLEWARE
|---------|---------|---------|--------|-----------|-------------------|------------|
  default | default | :8888   | GET    | /template | main.main.func1.1 |
|---------|---------|---------|--------|-----------|-------------------|------------|

可以看到,配置文件被自動讀取并應(yīng)用到了?WebServer?上。

我們通過?curl?命令測試一下靜態(tài)文件以及模板引擎的訪問。

$ curl http://127.0.0.1:8888/
Hello!

$ curl http://127.0.0.1:8888/template
Hello GoFrame!

可以看到,?index.html?靜態(tài)文件以及?index.tpl?模板文件都被成功訪問到了。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號