登录
首页 >  Golang >  Go问答

文件在非根目录下时出现404错误

来源:stackoverflow

时间:2024-02-24 13:54:25 197浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《文件在非根目录下时出现404错误》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在运行此命令“go run webapp/main.go”。原因是应用程序引擎将从根目录调用我的应用程序,因此我更改了从根目录调用文件的工作路径。我也不介意您是否有 go 最佳实践技巧。

└── webapp
    ├── app.yaml
    ├── assets
    │   ├── css
    │   │   └── index.css
    │   └── img
    ├── main.go
    ├── main_test.go
    └── templates
        └── index.html

对于如此微不足道的事情怎么会出错感到困惑。 localhost:8080/css/index.css 工作正常。我还有另一个处理程序函数来服务 localhost:8080/static/css/index.css,但我收到 404 错误。当我使用命令“go run main.go”并从代码中删除“webapp”时,一切都运行顺利。不过,它如何与 / 一起工作而不是与 /static/ 一起工作。正如在此 https://stackoverflow.com/a/47997908/6828897 答案中所示,它应该将 ./webapp/assets/static 作为目录。我也尝试过 http.stripprefix 但也没有运气。

package main

import (
    "flag"
    "log"
    "net/http"
    "os"
    "path/filepath"
    "sync"
    "text/template"
)

type templateHandler struct {
    once     sync.Once
    filename string
    templ    *template.Template
}

// ServeHTTP handles the HTTP request.
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    t.once.Do(func() {
        t.templ = template.Must(template.ParseFiles(filepath.Join("webapp", "templates", t.filename)))
    })
    if err := t.templ.Execute(w, r); err != nil {
        log.Printf("Error executing template: %v", err)
        http.Error(w, "Internal server error", http.StatusInternalServerError)
    }
}

func main() {
    dir, err := os.Getwd()
    if err != nil {
        log.Printf(err.Error())
    }
    log.Printf("dir: %s", dir)

    // command flags
    var addr = flag.String("addr", ":8080", "The addr of the application.")
    flag.Parse()

    // env variables
    envPort := os.Getenv("PORT")
    if envPort != "" {
        envPort = ":" + envPort
        addr = &envPort
    }

    fs := http.FileServer(http.Dir("./webapp/assets"))
    http.Handle("/static/", fs)

    log.Printf("Listening on port %s", *addr)

    // http.Handle("/", &templateHandler{filename: "index.html"})

    if err := http.ListenAndServe(*addr, fs); err != nil {
        log.Fatal(err)
    }
}

解决方案


“它如何与 / 一起使用而不是 /static/”

因为您将 fs 直接传递给 listenandserve,这意味着 http.handle("/static/", fs) 使用的 DefaultServeMux 被忽略/覆盖。

http.Handle

http.ListenAndServe

所以一般来说你应该做的是这样的:

fs := http.FileServer(http.Dir("./webapp/assets"))
// register fs for "/static/" in DefaultServeMux
http.Handle("/static/", fs)
// start listening at addr and serve incoming requests
// using DefaultServeMux as the router (because nil).
if err := http.ListenAndServe(*addr, nil); err != nil {
    log.Fatal(err)
}

如果您的设置中存在其他问题,您的应用可能无法立即按预期运行,但是此更改肯定是接近该目标的必要条件。

好了,本文到此结束,带大家了解了《文件在非根目录下时出现404错误》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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