doujiu4643 2017-09-22 19:39
浏览 46
已采纳

Go不会为所有HTML页面呈现CSS元素

I am a novice at go programming. I followed this (https://golang.org/doc/articles/wiki/) tutorial. I wanted to build on top of this a site with multiple pages and CSS elements.

In the main method I used

http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css")))) 

This is my makeHandler function. It is supposed to direct all requests to the correct handler.

func makeHandler( fn func( http.ResponseWriter, *http.Request, string)) http.HandlerFunc{
    return func( w http.ResponseWriter, r *http.Request ){
            //extract page title from request
            //and call the provided handler 'fn'
            m := validPath.FindStringSubmatch(r.URL.Path)
            fmt.Println(m)
            if m == nil{
                    http.NotFound(w,r)
                    return
            }
            fn(w,r,m[2])
    }

}

When I printed 'm', all the requests were prefixed by view (I have a viewHandler that is then called to render the templates).

        http.HandleFunc("/view/", makeHandler(viewHandler))

So if I wanted to view an aboutSite page, the url would have /view/aboutSite which would then be directed to viewHandler.

The issue is that the html templates have CSS links and the links are being prefixed by 'view' as well. So if I had this line of code in my html template

<link rel="stylesheet" href="css/bootstrap.min.css">

makeHandler would receive a 'view' prefixed url. /view/css/bootstrap.min.css

what do I need to add/change so that the CSS elements are rendered?

  • 写回答

1条回答 默认 最新

  • douqixia7942 2017-09-23 00:07
    关注

    You need to use absolute paths in the href attribute (i.e. use a path which starts with a /), otherwise the path is treated as relative to the current page leading to the behaviour you are seeing.

    So for example:

    <link rel="stylesheet" href="/css/bootstrap.min.css">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab用simulink求解一个二阶微分方程
  • ¥30 matlab解优化问题代码
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?