我看到的問題是,我試圖使用http.FileServer
Gorilla mux Router.Handle函數。Golang Gorilla多路複用器與http.FileServer返回404
這不起作用(圖像返回404)..
myRouter := mux.NewRouter()
myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
這個工程(圖像顯示OK)..下面
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
簡約歸Web服務器程序,顯示問題...
package main
import (
"fmt"
"net/http"
"io"
"log"
"github.com/gorilla/mux"
)
const (
HomeFolder = "/root/test/"
)
func HomeHandler(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, htmlContents)
}
func main() {
myRouter := mux.NewRouter()
myRouter.HandleFunc("/", HomeHandler)
//
// The next line, the image route handler results in
// the test.png image returning a 404.
// myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
//
myRouter.Host("mydomain.com")
http.Handle("/", myRouter)
// This method of setting the image route handler works fine.
// test.png is shown ok.
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
// HTTP - port 80
err := http.ListenAndServe(":80", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
fmt.Printf("ListenAndServe:%s\n", err.Error())
}
}
const htmlContents = `<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Test page</title>
<meta charset = "UTF-8" />
</head>
<body>
<p align="center">
<img src="/images/test.png" height="640" width="480">
</p>
</body>
</html>
`
+1#2在我當前的項目中取得了成功(在我偶然發現這個答案之前,讓讀者確信#2是我正在使用和工作的)。 – eduncan911
+1 - #2也適用於我 – Aaron
只需添加註釋,請記住,如果您是像我這樣的golang新手,golang不會喜歡#2格式的語句。在golang停止抱怨期待逗號之前,我需要將所有三行代碼合併成一行(語法沒有變化,只是改變空格)。 #2是正確的答案,它只是以這種方式形成的,這會給像我這樣的新手和新手帶來問題。 –