gpt4 book ai didi

go - Gorilla mux 路由器不提供静态内容——比如 style.css、script.js

转载 作者:数据小太阳 更新时间:2023-10-29 03:12:50 27 4
gpt4 key购买 nike

我是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语言上我花了一整天但是无法解决问题。你的帮助是适当的。

提前致谢。

最佳答案

正如 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 请求将返回 style.css 来自相对 ./public/css/ 目录。

关于go - Gorilla mux 路由器不提供静态内容——比如 style.css、script.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46515542/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com