나는 분명히 뭔가를 간과 한 적이 확실하지만 무엇이 확실하지 않습니다. 나는 템플릿의 페이지를 제공하는 간단한 웹 애플리케이션을 만들고있다. 템플릿이 제대로 작동하고 이미지의 경로가 제대로 채워지는 것처럼 보이지만 이미지 자체에 404 오류가 계속 발생합니다. 여기 Golang 웹 서버가 정적 파일을 제공하지 않음
템플릿입니다 :<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
@Flimzy 당신이 맞습니다, 그것은 제대로'./images /'이어야합니다, 그러나 문제는 어느쪽으로 든 지속됩니다. – FreeRangeOyster
디렉토리 구조와 서버 시작 방법을 알 수 없지만 이러한 대답에는 해결책이 포함되어 있습니다. [404 페이지를 찾을 수 없음 - css 파일로 이동] (http://stackoverflow.com/questions/28293452/404-page) -not-found-go-rendering-css-file/28294524 # 28294524); 왜 내 정적 파일에 액세스하려면 http.StripPrefix를 사용해야합니까?] (http://stackoverflow.com/questions/27945310/why-do-i-need-to-use-http-stripprefix-to-access -my-static-files/27946132 # 27946132) – icza