douzhou7124 2017-05-11 08:14
浏览 60
已采纳

Golang Web服务器不提供静态文件

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:

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

and here is the application itself:

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())
}

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条回答 默认 最新

  • dtqie02844 2017-05-13 16:09
    关注

    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("./images/"))
    router.PathPrefix("/images/").Handler(http.StripPrefix("/images/", imgServer))
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系