登录
首页 >  Golang >  Go问答

Go http.Handle() 未按预期工作。 404 文件未找到

来源:stackoverflow

时间:2024-04-09 13:30:40 319浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《Go http.Handle() 未按预期工作。 404 文件未找到》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

因此,我尝试使用我的 go 服务器让 css 工作,但 css 文件未正确加载,我得到 404 文件未找到 。当我直接从浏览器运行 index.html 时,它工作正常。

我的目录结构,其中 # 代表文件夹,- 代表文件:

- main.go
# static
    - index.html
    # css
       - styles.css

index.html 包含:

这些是我的所有处理程序:

muxrouter := mux.newrouter()
muxrouter.handlefunc("/", basichandler)
muxrouter.handlefunc("/ws", wshandler)
muxrouter.handle("/css/", http.stripprefix("/css/", http.fileserver(http.dir("static/css"))))

basichandler 包含:

toSend := template.HTMLEscapeString(outputMessage)
toSend = strings.Replace(toSend, "\n", "
", -1) templateError := allTemplates.ExecuteTemplate(responseWriter, "index.html", template.HTML(toSend)) if templateError != nil { log.Fatal("Template error: ", templateError) }

wshandler 处理我的程序使用的 websocket。


解决方案


我建议像这样移动你的文件(注意我将 index.html 重命名为小写 - 因此在访问文档根 url 时它将默认加载):

main.go
static/
static/index.html
static/css/styles.css

修改 index.html 以引用更恰当命名的 css 目录:

编辑:更新以适应 gorilla/mux。

致电 answer

package main

import (
        "github.com/gorilla/mux"
        "log"
        "net/http"
)

func main() {
        r := mux.NewRouter()

        r.PathPrefix("/css/").Handler(
                http.StripPrefix("/css/", http.FileServer(http.Dir("static/css/"))),
        )   

        err := http.ListenAndServe(":8080", r)
        if err != nil {
                log.Fatal(err)
        }   

        // curl 'localhost:8080/css/Styles.css'
        // 
}

本篇关于《Go http.Handle() 未按预期工作。 404 文件未找到》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>