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">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP