---
title: "资源管理-使用示例"
url: "https://goframe.org/docs/core/gres-example"
markdown_url: "https://goframe.org/docs/core/gres-example.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "核心组件"
category: "核心组件 / 资源管理"
published: "2024-10-21"
updated: "2026-02-11"
description: "通过完整示例展示`GoFrame`框架资源管理组件在实际项目中的应用。演示了资源管理在`WebServer`的静态服务、配置管理和模板引擎中的集成使用。展示资源文件的组织结构和打包方式，包括配置文件`config.toml`、静态资源`index.html`和模板文件`index.tpl`。通过简单的`import`引入就能实现资源文件的自动加载，无需对代码做额外设置，充分体现`GoFrame`资源管理的便捷性。"
keywords: ["GoFrame", "GoFrame框架", "资源管理", "WebServer", "静态服务", "配置管理", "模板引擎", "资源文件", "示例", "编程"]
---

# 资源管理-使用示例

我们来看一个使用示例，在该示例中，展示了资源管理在`WebServer`的静态服务、配置管理、模板引擎中的使用。

### 资源文件

资源文件源码： [https://github.com/gogf/gf/tree/master/os/gres/testdata/example/files](https://github.com/gogf/gf/tree/master/os/gres/testdata/example/files)

资源文件打包： [https://github.com/gogf/gf/tree/master/os/gres/testdata/example/boot](https://github.com/gogf/gf/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
```

三个文件的内容分别为：

1. `config.toml`

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

    [viewer]
        DefaultFile = "index.tpl"
        Delimiters  = ["${", "}"]
```

该文件为应用的配置文件。

2. `index.html`

```html
    Hello!
```

该文件用于静态资源请求。

3. `index.tpl`

```html
    Hello ${.name}!
```

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

### 创建应用

```go
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"`的包引入外，没有其他任何设置。这也是`GoFrame`框架的资源管理比较便捷的地方，资源管理并不需要开发阶段对代码做任何特殊设置，在应用程序部署之前打包好资源文件，并通过`import`增加资源文件的引入即可。

运行后，终端输出：

```html
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 |
|---------|---------|---------|--------|-----------|-------------------|------------|
```

可以看到，配置文件被自动读取并应用到了`WebServer`上。

我们通过`curl`命令测试一下静态文件以及模板引擎的访问。

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

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

可以看到，`index.html`静态文件以及`index.tpl`模板文件都被成功访问到了。
