首页 > 解决方案 > 如何提供 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。我不知道如何同时拥有这两个功能。

标签: httpgoserver

解决方案


您的原始解决方案几乎就在那里,您所要做的就是添加一个分支:

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


推荐阅读