简体   繁体   English

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

[英]Go is not rendering CSS elements for all HTML pages

I am a novice at go programming. 我是Go编程的新手。 I followed this ( https://golang.org/doc/articles/wiki/ ) tutorial. 我遵循了这个( https://golang.org/doc/articles/wiki/ )教程。 I wanted to build on top of this a site with multiple pages and CSS elements. 我想在此基础上构建一个包含多个页面和CSS元素的网站。

In the main method I used 在我使用的主要方法中

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

This is my makeHandler function. 这是我的makeHandler函数。 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). 当我打印'm'时,所有请求都以view为前缀(我有一个viewHandler,然后调用它来渲染模板)。

        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. 因此,如果我想查看aboutSite页面,则该URL将具有/ view / aboutSite,然后将其定向到viewHandler。

The issue is that the html templates have CSS links and the links are being prefixed by 'view' as well. 问题在于html模板具有CSS链接,并且这些链接也以“ view”作为前缀。 So if I had this line of code in my html template 因此,如果我的html模板中有这行代码

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

makeHandler would receive a 'view' prefixed url. makeHandler会收到一个以“ view”为前缀的URL。 /view/css/bootstrap.min.css /view/css/bootstrap.min.css

what do I need to add/change so that the CSS elements are rendered? 我需要添加/更改什么以便呈现CSS元素?

You need to use absolute paths in the href attribute (ie 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. 您需要在href属性中使用绝对路径(即,使用以/开头的路径),否则该路径将被视为相对于当前页面的相对路径,从而导致您看到的行为。

So for example: 因此,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM