Golang web服务器无法提供静态文件。

huangapple go评论89阅读模式
英文:

Golang web server not serving static files

问题

我相当确定我忽视了一些明显的东西,但我不确定是什么。我正在构建一个简单的网络应用程序,用于提供书籍的模板页面。模板本身工作正常,图像路径似乎正确,但是图像本身却一直显示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错误。我在这里缺少了哪些配置或路由选项?

英文:

I'm fairly certain that I've overlooked something obvious, but I'm not sure what. I'm building a simple web application that serves up templated pages of books. The template works fine, and the path for the image seems to be populating correctly, but I keep getting a 404 error for the image itself.

Here is the template:
<!-- language: html -->

&lt;h1&gt;{{.Title}}&lt;/h1&gt;
&lt;h2&gt;{{.Author.Name}}&lt;/h2&gt;
&lt;image src=&quot;../images/{{.ImageURI}}&quot; /&gt;

and here is the application itself:
<!-- language: go -->

package main
import (
&quot;html/template&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;time&quot;
&quot;github.com/gorilla/mux&quot;
&quot;github.com/user/marketplace/typelibrary&quot;
)
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[&quot;id&quot;] {
selected = item
break
}
}
t, _ := template.ParseFiles(&quot;./templates/book.html&quot;)
t.Execute(w, selected)
}
func main() {
router := mux.NewRouter()
books = append(books, typelibrary.Book{ID: &quot;1&quot;, Title: &quot;The Fellowship of the Ring&quot;, ImageURI: &quot;LotR-FotR.jpg&quot;, Author: &amp;typelibrary.Author{Name: &quot;JRR Tolkien&quot;}})
books = append(books, typelibrary.Book{ID: &quot;2&quot;, Title: &quot;The Two Towers&quot;, ImageURI: &quot;LotR-tTT.jpg&quot;, Author: &amp;typelibrary.Author{Name: &quot;JRR Tolkien&quot;}})
books = append(books, typelibrary.Book{ID: &quot;3&quot;, Title: &quot;The Return of the King&quot;, ImageURI: &quot;LotR-RotK.jpg&quot;, Author: &amp;typelibrary.Author{Name: &quot;JRR Tolkien&quot;}})
books = append(books, typelibrary.Book{ID: &quot;4&quot;, Title: &quot;Monster Hunter International&quot;, ImageURI: &quot;MHI1.jpg&quot;, Author: &amp;typelibrary.Author{Name: &quot;Larry Correia&quot;}})
router.Handle(&quot;/&quot;, http.FileServer(http.Dir(&quot;.&quot;)))
router.Handle(&quot;/images/&quot;, http.FileServer(http.Dir(&quot;../images/&quot;)))
router.HandleFunc(&quot;/item/{id}&quot;, ItemHandler).Methods(&quot;GET&quot;)
srv := &amp;http.Server{
Handler:      router,
Addr:         &quot;:8080&quot;,
WriteTimeout: 10 * time.Second,
ReadTimeout:  10 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}

The images are stored in the images subdirectory, directly below the directory where the executable is. When I attempt to view the broken image in the page, the path shows up as localhost:8080/images/[imagename] but gives a 404 error. What configuration or routing options am I missing here?

答案1

得分: 8

你正在错误地创建你的路由以提供图像。Router.Handle() 方法使用 Path() 匹配器来匹配 URL,该匹配器匹配整个路径,而你实际上想要匹配任何以 "/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

英文:

You are creating your route incorrectly to serve your images. The Router.Handle() method matches URLs with the Path() matcher, which matches the entire path, while you actually want to match any path that starts with "/image/". Instead, create the route with the PathPrefix() matcher:

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

See https://godoc.org/github.com/gorilla/mux#Router.Handle for more information.

huangapple
  • 本文由 发表于 2017年5月11日 16:14:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/43909971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定