Let’s look at a usage example, which demonstrates the use of resource management in the static service, configuration management, and template engine of a WebServer
.
Resource Files
Source code of resource files: https://github.com/gogf/gf/tree/master/os/gres/testdata/example/files
Resource file packaging: https://github.com/gogf/gf/tree/master/os/gres/testdata/example/boot
List of resource files:
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
The contents of the three files are as follows:
config.toml
[server]
Address = ":8888"
ServerRoot = "public"
[viewer]
DefaultFile = "index.tpl"
Delimiters = ["${", "}"]
This file is the configuration file for the application.
index.html
Hello!
This file is used for static resource requests.
index.tpl
Hello ${.name}!
This file is used for template file parsing and display.
Creating the Application
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()
}
As you can see, besides an additional package import _ "github.com/gogf/gf/v2/os/gres/testdata/example/boot"
, the entire code has no other settings. This is the convenience of resource management in the GoFrame
framework, as resource management does not require any special configuration during the development phase. By packaging the resource files before the application is deployed and adding the resource files via import
, resource management is achieved.
After running, the terminal outputs:
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 |
|---------|---------|---------|--------|-----------|-------------------|------------|
You can see that the configuration file has been automatically read and applied to the WebServer
.
Let’s use the curl
command to test accessing static files and the template engine.
$ curl http://127.0.0.1:8888/
Hello!
$ curl http://127.0.0.1:8888/template
Hello GoFrame!
You can see that the index.html
static file and the index.tpl
template file were both accessed successfully.