在 Web 开发中,除了提供 API 接口外,往往还需要对外提供静态资源服务,比如:
- • CSS 样式文件
- • JavaScript 脚本
- • 图片、字体等静态资源
Go 的 net/http
包和 Gin 框架都提供了方便的方式来托管这些静态文件。
本篇我们将用 Gin 框架 演示如何快速构建一个静态资源服务。
一、功能目标
-
- 使用 Gin 提供一个静态资源目录,让用户能直接访问 CSS、JS、图片。
-
- 演示 HTML 页面引入这些静态资源。
-
- 支持前端直接访问
/static/...
路径获取文件。
- 支持前端直接访问
二、项目结构
假设我们的项目目录结构如下:
arduino
project/
│── main.go
│── static/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── app.js
│ └── images/
│ └── logo.png
└── templates/
└── index.html
三、代码实现
go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
// 1. 加载模板
r.LoadHTMLGlob("templates/*")
// 2. 提供静态文件服务
// /static 对应项目下的 static 目录
r.Static("/static", "./static")
// 3. 首页路由
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)
})
// 启动服务器
r.Run(":8080")
}
四、HTML 模板示例
templates/index.html
:
xml
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>静态资源示例</title>
<!-- 引入 CSS -->
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<h1>欢迎来到 Go 静态资源服务示例</h1>
<!-- 引入图片 -->
<img src="/static/images/logo.png" alt="Logo" width="150">
<!-- 引入 JS -->
<script src="/static/js/app.js"></script>
</body>
</html>
五、静态资源示例
static/css/style.css
:
css
body {
background-color: #f5f5f5;
font-family: Arial, sans-serif;
text-align: center;
}
h1 {
color: #333;
}
static/js/app.js
:
javascript
document.addEventListener("DOMContentLoaded", function() {
console.log("JavaScript 已加载");
});
六、运行与访问
运行服务:
go
go run main.go
在浏览器访问:
arduino
http://localhost:8080/
你会看到页面正常加载了 CSS 样式、图片和 JavaScript 脚本。
静态资源也可以直接访问:
bash
http://localhost:8080/static/images/logo.png
http://localhost:8080/static/css/style.css
七、总结
- • Gin 提供
Static()
方法一行就能完成静态文件托管。 - • 静态文件路径映射和 URL 前缀可以灵活配置。
- • 结合 HTML 模板,可以很方便地构建完整的前端页面服务。