douzhang8033 2018-06-27 17:19
浏览 49
已采纳

如何提供CSS文件并进行动态路由?

I'm trying to set up an HTTP server in Go using only the standard library. The server should be able to accept requests of the form /:uuid and should be able to serve an index.html file as well as a css file imported in it. This is what my code looked like:

 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)
}

This serves the html file and is able to accept requests like /:something but the problem is that it doesn't include the CSS file. After some googling, I changed the main function to this:

func main() {
    fs := http.FileServer(http.Dir("web"))
    http.Handle("/", fs)
    log.Println("listening on port 5000")
    http.ListenAndServe(":5000", nil)
}

This serves both the HTML and the CSS files but it doesn't allow routes of the form :something. I can't figure out how to have both of these features.

  • 写回答

1条回答 默认 最新

  • duanjiao5723 2018-06-27 17:21
    关注

    Your original solution was nearly there, all you have to do is add a branch:

    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 {
        // ...
    

    Of course this can be tailored as needed - you could check for any file ending in ".css" using strings.HasSuffix, for example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示