【问题标题】:Golang web server not serving static filesGolang Web 服务器不提供静态文件
【发布时间】:2017-10-10 03:14:20
【问题描述】:

我很确定我忽略了一些明显的东西,但我不确定是什么。我正在构建一个简单的 Web 应用程序,用于提供模板化的书籍页面。模板工作正常,并且图像的路径似乎正确填充,但我不断收到图像本身的 404 错误。

这是模板:

<h1>{{.Title}}</h1>
<h2>{{.Author.Name}}</h2>
<image src="../images/{{.ImageURI}}" />

这是应用程序本身:

package main
import (
    "html/template"
    "log"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    "github.com/user/marketplace/typelibrary"
)

var books []typelibrary.Book

func ItemHandler(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    var selected typelibrary.Book       
    //Retrieve item data
    for _, item := range books {
        if item.ID == params["id"] {
            selected = item
            break
        }
    }
    t, _ := template.ParseFiles("./templates/book.html")
    t.Execute(w, selected)
}

func main() {
    router := mux.NewRouter()
    books = append(books, typelibrary.Book{ID: "1", Title: "The Fellowship of the Ring", ImageURI: "LotR-FotR.jpg", Author: &typelibrary.Author{Name: "JRR Tolkien"}})
    books = append(books, typelibrary.Book{ID: "2", Title: "The Two Towers", ImageURI: "LotR-tTT.jpg", Author: &typelibrary.Author{Name: "JRR Tolkien"}})
    books = append(books, typelibrary.Book{ID: "3", Title: "The Return of the King", ImageURI: "LotR-RotK.jpg", Author: &typelibrary.Author{Name: "JRR Tolkien"}})
    books = append(books, typelibrary.Book{ID: "4", Title: "Monster Hunter International", ImageURI: "MHI1.jpg", Author: &typelibrary.Author{Name: "Larry Correia"}})

    router.Handle("/", http.FileServer(http.Dir(".")))
    router.Handle("/images/", http.FileServer(http.Dir("../images/")))
    router.HandleFunc("/item/{id}", ItemHandler).Methods("GET")

    srv := &http.Server{
        Handler:      router,
        Addr:         ":8080",
        WriteTimeout: 10 * time.Second,
        ReadTimeout:  10 * time.Second,
    }
    log.Fatal(srv.ListenAndServe())
}

图像存储在images 子目录中,位于可执行文件所在目录的正下方。当我尝试查看页面中损坏的图像时,路径显示为localhost:8080/images/[imagename],但出现 404 错误。我在这里缺少哪些配置或路由选项?

【问题讨论】:

  • 您几乎可以肯定将错误的路径传递给http.Dir。为什么../?您是否从子目录执行服务器?根据您的描述,我希望您想要./images/
  • @Flimzy 你是对的,应该是./images/,但是问题仍然存在。
  • 我们不知道您的目录结构以及您如何启动服务器,但这些答案包含解决方案:404 page not found - Go rendering css file;和Why do I need to use http.StripPrefix to access my static files?
  • 这实际上取决于图像相对于执行二进制文件时的工作目录的位置。另一种方法是使用配置值(来自配置文件、环境变量或 CLI 标志)传入可以找到内容文件的根路径,并使用该路径而不是相对路径。
  • 要知道。 github.com/user/marketplace/typelibrary 是什么?

标签: go webserver http-status-code-404 static-files


【解决方案1】:

您创建的路线不正确,无法提供图片。 Router.Handle() 方法将 URL 与 Path() 匹配器匹配,该匹配器匹配整个路径,而您实际上想要匹配以“/image/”开头的任何路径。相反,使用 PathPrefix() 匹配器创建路由:

var imgServer = http.FileServer(http.Dir("./images/"))
router.PathPrefix("/images/").Handler(http.StripPrefix("/images/", imgServer))

更多信息请参见https://godoc.org/github.com/gorilla/mux#Router.Handle

【讨论】: