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:

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

The contents of the three files are as follows:

  1. config.toml
  1. [server]
  2. Address = ":8888"
  3. ServerRoot = "public"
  4. [viewer]
  5. DefaultFile = "index.tpl"
  6. Delimiters = ["${", "}"]

This file is the configuration file for the application.

  1. index.html
  1. Hello!

This file is used for static resource requests.

  1. index.tpl
  1. Hello ${.name}!

This file is used for template file parsing and display.

Creating the Application

  1. package main
  2. import (
  3. _ "github.com/gogf/gf/v2/os/gres/testdata/example/boot"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. func main() {
  8. s := g.Server()
  9. s.Group("/", func(group *ghttp.RouterGroup) {
  10. group.GET("/template", func(r *ghttp.Request) {
  11. r.Response.WriteTplDefault(g.Map{
  12. "name": "GoFrame",
  13. })
  14. })
  15. })
  16. s.Run()
  17. }

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:

  1. 2020-03-28 21:36:19.828 75892: http server started listening on [:8888]
  2. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  3. |---------|---------|---------|--------|-----------|-------------------|------------|
  4. default | default | :8888 | GET | /template | main.main.func1.1 |
  5. |---------|---------|---------|--------|-----------|-------------------|------------|

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.

  1. $ curl http://127.0.0.1:8888/
  2. Hello!
  3. $ curl http://127.0.0.1:8888/template
  4. Hello GoFrame!

You can see that the index.html static file and the index.tpl template file were both accessed successfully.