在遵循了一些教程和其他SO答案(在这里和这里)之后,我试图用Go提供静态文件,我到达了以下代码。我已经研究了许多其他类似的问题,但答案是不是为我工作。我实现的路由与大多数其他问题略有不同,因此我想知道是否存在一个导致问题的细微问题,但是不幸的是,我的Go技能还不够完善,无法看清问题所在。我的代码如下(我已经排除了处理程序的代码,因为它不相关)。
router.go
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Path).
Name(route.Name).
Handler(handler)
}
// This should work?
fs := http.FileServer(http.Dir("./static"))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
return router
}
routes.go
package main
import (
"net/http"
"web-api/app/handlers"
)
type Route struct {
Name string
Method string
Path string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
handlers.Index,
},
Route{
"Login",
"GET",
"/login",
handlers.GetLogin,
},
Route{
"Login",
"POST",
"/login",
handlers.PostLogin,
},
}
main.go
...
func main() {
router := NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
我的文件结构设置为:
- app
- main.go
- router.go
- routes.go
- static/
- stylesheets/
- index.css
由于某些原因,浏览器无法访问localhost:8080 / static / stylesheets / index.css
文件路径是相对于当前工作目录的,而不是引用该路径的源代码文件的。
应用程序的文件服务器配置假定该app
目录是当前工作目录。app
运行应用程序之前,将目录更改为目录。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句