http - 如何提供 CSS 文件并进行动态路由?
问题描述
我正在尝试仅使用标准库在 Go 中设置 HTTP 服务器。服务器应该能够接受表单的请求,/:uuid
并且应该能够提供index.html
文件以及其中导入的 css 文件。这就是我的代码的样子:
func indexHandler(w http.ResponseWriter, r *http.Request) {
// serve index.html
if r.URL.Path == "/" {
http.ServeFile(w, r, "./web/index.html")
} else {
// if the path is /randomwords, redirect to mapped URL
randomwords := r.URL.Path[1:]
url := getMappedURL(randomwords)
http.Redirect(w, r, url, http.StatusFound)
}
}
func main() {
http.HandleFunc("/", indexHandler)
log.Println("listening on port 5000")
http.ListenAndServe(":5000", nil)
}
这为 html 文件提供服务,并且能够接受类似的请求,/:something
但问题是它不包含 CSS 文件。经过一番谷歌搜索,我将主要功能更改为:
func main() {
fs := http.FileServer(http.Dir("web"))
http.Handle("/", fs)
log.Println("listening on port 5000")
http.ListenAndServe(":5000", nil)
}
这同时为 HTML 和 CSS 文件提供服务,但它不允许表单的路由:something
。我不知道如何同时拥有这两个功能。
解决方案
您的原始解决方案几乎就在那里,您所要做的就是添加一个分支:
if r.URL.Path == "/" {
http.ServeFile(w, r, "./web/index.html")
} else if r.URL.Path == "/styles.css" {
http.ServeFile(w, r, "./web/styles.css")
} else {
// ...
当然,这可以根据需要进行定制——例如,您可以使用 .css 检查任何以“.css”结尾的文件strings.HasSuffix
。
推荐阅读
- infix-notation - 如何在 Android 中正确使用中缀表示法(Kotlin 语言)?
- java - 如何使用意图将变量从 MainActivity 传递到 ListAdapter
- ruby-on-rails - 如何通过 SwiftUI urlSession 中的 REST API 将图像数组上传到 Rails 活动存储后端
- html - 我将如何创建一个具有 1 个输入和 6 个不同输出的价格计算器?
- webpack - Webpack 控制台输出
- css - 在滚动负载上居中元素
- javascript - Vue 在每次小的更改时都会不必要地重新渲染整个所有子组件
- xslt-1.0 - 根据条件应用 XSLT
- php - 多个 And 是否在 mysql 中工作
- python - 如何在行数据框中选择数据 3 次更大的阈值 - 熊猫