【问题标题】:Golang mux http.FileServer not returning imageGolang mux http.FileServer不返回图像
【发布时间】:2020-02-19 04:36:11
【问题描述】:

我是新手,正在尝试设置 Go 服务器。我的目的是在点击 url 时返回一张图片。

这就是我所做的

myRouter := mux.NewRouter()
myRouter.HandleFunc("/poster_path/{id}",posterfunc)

这是我的海报功能

func posterfunc(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "image/jpeg")
    vars := mux.Vars(r)
    key := vars["id"]
    var url = "/home/rakshithjk/Desktop/poster/"+key+".jpg"
    http.FileServer(http.Dir(url))
}

这是 Postman 中的输出 -

任何帮助将不胜感激。

更新 - 尝试将http.FileServer 更改为http.ServeFile,但输出保持不变 修改处理函数

func posterfunc(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "image/jpeg")
    vars := mux.Vars(r)
    key := vars["id"]
    var url = "/home/rakshithjk/Desktop/poster/"+key+".jpg"
    http.ServeFile(w, r,url)

这是我的全部文件内容(供参考)

package main

import (
    "fmt"
    "log"
    "net/http"
    "encoding/json"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    //"github.com/davecgh/go-spew/spew"
)


func handleRequests() {
    myRouter := mux.NewRouter()
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/movie/top_rated", returnSingleArticle)
    myRouter.HandleFunc("/poster_path",posterfunc)

    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

func enableCors(w *http.ResponseWriter) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")

}
type movie_list struct {
    Page int `json:"page"`
    Results []movie `json:"results"`
}
type movie struct {
    Id      int `json:"id"`
    Title   string `json:"title"`
    Language    string `json:"language"`
    Release_date string `json:"release_date"`
    Poster_path string `json:"poster_path"`
    Background_path string `json:"background_path"`
    Overview string `json:"overview"`
    Genre_ids string `json:"genre_ids"`
}

func posterfunc(w http.ResponseWriter, r *http.Request){
     w.Header().Set("Content-Type", "image/jpeg")
    //vars := mux.Vars(r)
    //key := vars["id"]
    enableCors(&w)

    var url = "/home/rakshithjk/go/src/clumio/112.png"
    fmt.Fprintf(w, "Hello, %q\n", url)
    http.ServeFile(w, r,url)
}

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
    //vars := mux.Vars(r)
    //key := vars["id"]
    enableCors(&w)
    db, err := sql.Open("mysql", "root:72574484@tcp(127.0.0.1:3306)/PicturePerfect")
             if err != nil {
                 fmt.Println(err)
                 }else{
                 fmt.Println("Connection Established")
             }
    rows,err:=db.Query("select * from movies limit 10")

         if err!=nil{
            fmt.Println(err)
         }

         var list movie_list
         var tag movie

         for rows.Next(){

             err:=rows.Scan(&tag.Id,&tag.Title,&tag.Language,&tag.Release_date,&tag.Poster_path,&tag.Background_path,&tag.Overview,&tag.Genre_ids)
             if err != nil {
             fmt.Println(err)
            }
            fmt.Println(tag.Id)
            list.Results = append(list.Results,tag)
         }

        err = rows.Err()
        if err != nil {
            fmt.Println(err)
        }

        defer db.Close()


            //fmt.Fprintf(w, "Hello, %q\n", list.Results[3])
            w.Header().Set("Content-Type", "application/json")
            json.NewEncoder(w).Encode(list) 
            //spew.Dump(list)
            //fmt.Fprintf(w, "given lamguage, %q\n", tag.Poster_path)



}

func main() {
    handleRequests()

}

【问题讨论】:

    标签: http go


    【解决方案1】:

    http.FileServer() 不应在这样的函数中调用。它返回一个Handler function(类似于您创建的posterfunc 的函数)。

    它应该像这样在路由配置中用作处理函数:

    myRouter.HandleFunc("/poster_path/",http.FileServer(http.Dir("./your_dir")))
    

    您可以在此处找到documentation for http.FileServer,并提供一些更详细的示例。

    This blog post 详细说明了如何设置它。

    更新:

    如果你想在你的处理程序中使用它,你应该使用http.ServeFile。它将使用命名文件或目录的内容响应请求。

    Docs here

    func posterfunc(w http.ResponseWriter, r *http.Request){
        w.Header().Set("Content-Type", "image/jpeg")
        vars := mux.Vars(r)
        key := vars["id"]
        var url = "/home/rakshithjk/Desktop/poster/"+key+".jpg"
        http.ServeFile(w, r, url)
    }
    

    更新 2:

    新的 sn-p 中的问题是您在提供文件之前打印到界面。 删除这一行:

    fmt.Fprintf(w, "Hello, %q\n", url)
    

    【讨论】:

    • 但是使用上述方法的问题是我的文件位置因url中的参数值而异。我如何合并它?
    • 我明白了。我正在更新我的回复
    • 我浏览了博文,提到http.ServeFile 用于在处理函数中提供文件。尝试合并,但仍然没有工作
    • 我更新了我的回复。你能试试吗?我将在这里创建一个简单的项目来测试它。
    • 我做了,但图像仍未显示为输出。它仍然在邮递员中显示与问题中提到的相同的输出