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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?