【发布时间】: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 我花了一整天但是 无法解决问题。 你的帮助是适当的。
提前致谢。
【问题讨论】: