我是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.When调用页面http://localhost:8080/css/bootstrap.min.css然后404 staus代码来
请帮助我在这里做错了什么。 我们可以在Java和Java服务器上轻松完成。但是在Go lang上我花了一整天但是 无法解决问题。 你的帮助是合适的。
提前致谢。
答案 0 :(得分:1)
正如mkopriva所说,http.FileServer
是要走的路。您的公用文件夹可以是您想要的任何地方或任何地方,只要它被正确引用为http.FileServer
参数。
添加它会起作用:
fs := http.FileServer(http.Dir("./public"))
gorillaRoute.PathPrefix("/js/").Handler(fs)
gorillaRoute.PathPrefix("/css/").Handler(fs)
这样,对GET
的{{1}}请求将从相对http://[host]:[port]/css/style.css
目录返回style.css
。