【问题标题】:Static content not served with the Gorilla mux router- like style.css,script.jsGorilla mux 路由器不提供静态内容,例如 style.css、script.js
【发布时间】:2023-03-30 21:02:01
【问题描述】:

我是 Go 语言的初学者。我试图用 Gorrila Mux 路由器提供静态容器。但 css 和 js 在我的情况下不是服务器。

  project
   f-mymux.go 
   d-pages
         f-home.html
         f-about.html
   d-public
        d-css
           f-style.css
        d-js
           f-script.js

注意:f-文件&d-目录

我的GO代码如下:

package main

import (
    "bufio"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    "os"
    "strings"
    "text/template"
)

func main() {
    serverWeb()
}

var staticPages = populateStaticPages()

func serverWeb() {
    gorillaRoute := mux.NewRouter().StrictSlash(true)
    gorillaRoute.HandleFunc("/", serveContent)
    gorillaRoute.HandleFunc("/{page_alias}", serveContent)
    gorillaRoute.HandleFunc("/css", serveResource)
    port := ":8080"
    log.Println("Listening at port :", port)
    http.Handle("/", gorillaRoute)
    err := http.ListenAndServe(port, nil)
    if err == nil {
        log.Fatal(err)
    }
}

func serveContent(w http.ResponseWriter, r *http.Request) {
    pathX := r.URL.Path
    log.Println(pathX)
    urlParams := mux.Vars(r)
    page_alias := urlParams["page_alias"]
    if page_alias == "" {
        page_alias = "home"
    }
    staticPage := staticPages.Lookup(page_alias + ".html")
    if staticPage == nil {
        staticPage = staticPages.Lookup("404.html")
        w.WriteHeader(404)
    }
    staticPage.Execute(w, nil)
}

func populateStaticPages() *template.Template {
    result := template.New("template")
    templatePaths := new([]string)
    basePath := "pages"
    templateFolder, _ := os.Open(basePath)
    defer templateFolder.Close()
    templatePathsRow, _ := templateFolder.Readdir(-1)
    for _, pathInfo := range templatePathsRow {
        log.Println(pathInfo.Name())
        *templatePaths = append(*templatePaths, basePath+"/"+
            pathInfo.Name())
    }
    result.ParseFiles(*templatePaths...)
    return result
}

//---------------------------------------------
// Serve resource of types css, js & img files
//---------------------------------------------

func serveResource(w http.ResponseWriter, r *http.Request) {
    path := "./public" + r.URL.Path
    var contentType string
    if strings.HasSuffix(path, ".css") {
        contentType = "text/css; charset=utf-8"
    } /* else if strings.HasSuffix(path , ".png"){
        contentType = "image/png; charset=utf-8"
       } else if strings.HasSuffix(path , ".jpg"){
        contentType = "image/jpg; charset=utf-8"
       } else if strings.HasSuffix(path , ".js"){
       contentType = "application/javascript; charset=utf-8"
       } else {
         contentType = "text/plain; charset=utf-8"
       }*/

    f, err := os.Open(path)
    if err == nil {
        defer f.Close()
        w.Header().Add("Content-Type", contentType)
        br := bufio.NewReader(f)
        br.WriteTo(w)
    } else {
        w.WriteHeader(404)
    }
}

当我调用代码时 http://localhost:8080/home 然后页面没有css和js。当调用页面http://localhost:8080/css/bootstrap.min.css然后404状态代码来

请帮助我这里做错了什么。 我们可以在 Java 和 Java 服务器上轻松完成。但是在 Go lang 我花了一整天但是 无法解决问题。 你的帮助是适当的。

提前致谢。

【问题讨论】:

  • 使用http.FileServer,如大猩猩自述文件here中所述。
  • 感谢回复 :-) 我想知道公用文件夹是否在应用程序内

标签: go gorilla


【解决方案1】:

正如 mkopriva 所说,http.FileServer 是要走的路。您的公用文件夹可以位于任何您想要的位置或任何位置,只要它被正确引用为 http.FileServer 参数即可。

添加它会起作用:

fs := http.FileServer(http.Dir("./public"))
gorillaRoute.PathPrefix("/js/").Handler(fs)
gorillaRoute.PathPrefix("/css/").Handler(fs)

这样,对http://[host]:[port]/css/style.cssGET 请求将从相关的./public/css/ 目录返回style.css

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2014-09-08
    • 2016-04-07
    • 2015-06-09
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多