登录
首页 >  Golang >  Go问答

子路由器无法正常运作,需要解决

来源:stackoverflow

时间:2024-03-24 15:18:39 151浏览 收藏

本文档讨论了子路由器出现的问题。第一个问题是 CSS 文件无法正确渲染,导致浏览器拒绝应用样式表,原因是其 MIME 类型为“text/plain”,不被支持。第二个问题是 HTML 渲染不一致,只有“/”路径下的页面可以显示,其他页面则显示 404 错误。为了解决这些问题,作者尝试了多种方法,包括使用 MIME 包设置正确的 MIME 类型,但均未成功。作者推测,正斜杠(“/”)的存在可能会影响页面呈现。

问题内容

我有一个这样的路由器

r := mux.newrouter()
    r.pathprefix("/static/styles/").handler(http.stripprefix("/static/styles/",
        http.fileserver(http.dir("static/styles"))))

    book := r.pathprefix("/books").subrouter()
    book.handlefunc("/issued-books/", issuedbooks)
    book.handlefunc("/top-trending/", showtoptrending)
    book.handlefunc("/", showallbooks)
    book.handlefunc("/available/", showavailable)

    r.handlefunc("/", showhome)

    http.listenandserve(":8080", r)

基本的处理函数结构如下:

func showavailable(w http.responsewriter, r *http.request) {

        tmp := store{}

        for ix, val := range json.books {
               status := &val.issuestatus
               if *status == false {
                     tmp.books = append(tmp.books, json.books[ix])
                }
         }
         rendertemplate(&w, "available.html", &tmp)
    }

rendertemplate 的定义如下:

func renderTempate(w *http.ResponseWriter, filename string, tmp *Store) {

    path := "static/" + filename
    tmpl := template.Must(template.ParseFiles(path))

    buf := new(bytes.Buffer)

    if err := tmpl.ExecuteTemplate(buf, filename, *tmp); err != nil {
           http.Error(*w, err.Error(), http.StatusInternalServerError)
           return
    }
     mime.AddExtensionType(".css", "text/css; charset=utf-8")
    res := *w
    res.Write(buf.Bytes())
    res.(http.Flusher).Flush()
}

第一个问题是它永远不会正确渲染 css 文件....浏览器最终总是说.... 拒绝从 /path/to/css 应用样式表...因为它的 mime 类型('text/plain')不是受支持的样式表 mime 类型...并且我尝试使用 mime 包来正确设置它然后将处理后的模板发送给客户端,但仍然无法工作。

第二个问题是 html 渲染变得不一致......只有 showallbooks 页面显示,其他页面没有显示, 给出 404 错误...为此,我尝试从 url 路径中删除正斜杠并显示所有页面...因此正斜杠会影响页面呈现...非常感谢任何帮助


解决方案


删除路线结尾的斜杠:

    book.HandleFunc("/issued-books", IssuedBooks)
    book.HandleFunc("/top-trending", ShowTopTrending)
    book.HandleFunc("/", ShowAllBooks)
    book.HandleFunc("/available", ShowAvailable)

go 开箱即用地支持 css - https://github.com/golang/go/blob/master/src/mime/type.go#L60

检查服务器返回的 css 链接到底是什么。会是404吗?

本篇关于《子路由器无法正常运作,需要解决》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>