我无法让子路由器正常工作

问题描述 投票:0回答:1

我有这样的路由器

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路径中删除正斜杠,并显示所有页面...因此,正斜杠会影响页面呈现...深深感谢您的帮助

http go server routing
1个回答
0
投票

删除路线末尾的斜线:


    book.HandleFunc("/issued-books", IssuedBooks)
    book.HandleFunc("/top-trending", ShowTopTrending)
    book.HandleFunc("/", ShowAllBooks)
    book.HandleFunc("/available", ShowAvailable)
© www.soinside.com 2019 - 2024. All rights reserved.