亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Gorilla Golang Pathprefix 不提供文件

Gorilla Golang Pathprefix 不提供文件

Go
嗶嗶one 2023-03-29 17:06:15
files我的 Golang 項目目錄根目錄中的文件夾中有一個名為test.jpg. 那就是./files/test.jpg 我想服務于我的前端,但我遇到了困難。我的 golang 項目在一個附有以下卷的 docker 文件中。(基本上就是說在docker容器里可以在服務器上/go/.../webserver讀寫出來)./volumes:  - ./:/go/src/github.com/patientplatypus/webserver/我正在使用gorilla/mux由以下定義的路由:r := mux.NewRouter()以下是我嘗試使 PathPrefix 正確格式化的一些嘗試:r.PathPrefix("/files/").Handler(http.StripPrefix("/files/", http.FileServer(http.Dir("/go/src/github.com/patientplatypus/webserver/files/"))))或者r.PathPrefix("/files").Handler(http.FileServer(http.Dir("./files/")))或者r.PathPrefix("/files/").Handler(http.StripPrefix("/files/",  http.FileServer(http.Dir("./"))))或者r.PathPrefix("/files/").Handler(http.FileServer(http.Dir("/go/src/github.com/patientplatypus/webserver/")))我之前使用以下命令成功寫入服務器:newPath := filepath.Join("/go/src/github.com/patientplatypus/webserver/files", "test.jpg")newFile, err := os.Create(newPath)所以我的直覺是,我的第一次嘗試應該是正確的,指定了整個路徑/go/.../files/。在任何情況下,我的每次嘗試都成功地將一個空的 response.data200OK返回到我的前端,如下所示:Object { data: "", status: 200, statusText: "OK",headers: {…}, config: {…}, request: XMLHttpRequest }它來自使用axios包的簡單 js 前端 http 請求:        axios({            method: 'get',            url: 'http://localhost:8000/files/test.jpg',        })        .then(response => {            //handle success            console.log("inside return for test.jpg and value             of response: ")            console.log(response);            console.log("value of response.data: ")            console.log(response.data)            this.image = response.data;        })        .catch(function (error) {            //handle error            console.log(error);        });關于為什么會發生這種情況,我唯一的猜測是它沒有看到該文件,因此什么也不返回。對于這樣一個看似微不足道的問題,我正處于猜測和檢查階段,不知道如何進一步調試。如果有人有任何想法,請告訴我。
查看完整描述

4 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

你能從中去掉 JavaScript 客戶端,并發出一個簡單的curl請求嗎?用簡單的文本文件替換圖像以消除任何可能的內容類型/MIME 檢測問題。


(稍微)調整文檔中發布的示例gorilla/mux:https://github.com/gorilla/mux#static-files


代碼


func main() {

    var dir string


    flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")

    flag.Parse()

    r := mux.NewRouter()


    r.PathPrefix("/files/").Handler(

        http.StripPrefix("/files/",

            http.FileServer(

                http.Dir(dir),

            ),

        ),

    )


    addr := "127.0.0.1:8000"

    srv := &http.Server{

        Handler:      r,

        Addr:         addr,

        WriteTimeout: 15 * time.Second,

        ReadTimeout:  15 * time.Second,

    }


    log.Printf("listening on %s", addr)

    log.Fatal(srv.ListenAndServe())

}

運行服務器


?  /mnt/c/Users/matt/Dropbox  go run static.go -dir="/home/matt/go/src/github.com/gorilla/mux"

2018/09/05 12:31:28 listening on 127.0.0.1:8000

獲取文件


?  ~  curl -sv localhost:8000/files/mux.go | head

*   Trying 127.0.0.1...

* Connected to localhost (127.0.0.1) port 8000 (#0)

> GET /files/mux.go HTTP/1.1

> Host: localhost:8000

> User-Agent: curl/7.47.0

> Accept: */*

>

< HTTP/1.1 200 OK

< Accept-Ranges: bytes

< Content-Length: 17473

< Content-Type: text/plain; charset=utf-8

< Last-Modified: Mon, 03 Sep 2018 14:33:19 GMT

< Date: Wed, 05 Sep 2018 19:34:13 GMT

<

{ [16384 bytes data]

* Connection #0 to host localhost left intact

// Copyright 2012 The Gorilla Authors. All rights reserved.

// Use of this source code is governed by a BSD-style

// license that can be found in the LICENSE file.


package mux


import (

        "errors"

        "fmt"

        "net/http"

請注意,實現此目的的“正確”方法是按照您的第一個示例:


r.PathPrefix("/files/").Handler(http.StripPrefix("/files/", 

http.FileServer(http.Dir("/go/src/github.com/patientplatypus/webserver/files/"))))

從路徑中刪除/files/前綴,這樣文件服務器就不會嘗試查找/files/go/src/...。

確保這/go/src/...是正確的——您提供的是從文件系統根目錄開始的絕對路徑,而不是從您的主目錄開始的(這是您的意圖嗎?)

如果這是您的意圖,請確保/go/src/...運行您的應用程序的用戶可以讀取它。


查看完整回答
反對 回復 2023-03-29
?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

所以,這不是一個很好的解決方案,但它(目前)有效。我看到了這個帖子:Golang。用什么?http.ServeFile(..) 還是 http.FileServer(..)?,顯然您可以使用較低級別的 apiservefile而不是添加了保護的文件服務器。


所以我可以使用


r.HandleFunc("/files/{filename}", util.ServeFiles)



func ServeFiles(w http.ResponseWriter, req *http.Request){

    fmt.Println("inside ServeFiles")

    vars := mux.Vars(req)

    fileloc := "/go/src/github.com/patientplatypus/webserver/files"+"/"+vars["filename"]

    http.ServeFile(w, req, fileloc)

}

再次不是一個很好的解決方案,我并不興奮 - 我將不得不在獲取請求參數中傳遞一些身份驗證內容以防止 1337h4x0rZ。如果有人知道如何啟動和運行 pathprefix,請告訴我,我可以重構。感謝所有幫助過的人!


查看完整回答
反對 回復 2023-03-29
?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

我通常只是將文件資產捆綁到我編譯的應用程序中。然后應用程序將以相同的方式運行和檢索資產,無論您是在容器中運行還是在本地運行。我過去使用過 go-bindata,但看起來這個包似乎不再維護,但有很多替代品可用。



查看完整回答
反對 回復 2023-03-29
?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

我和你在同一頁上,完全一樣,我一直在調查這件事,讓它工作一整天。我卷曲了,它也像你在上面的評論中提到的那樣給了我 200 個 0 字節。我在責怪碼頭工人。


它終于奏效了,唯一的 (...) 變化是我刪除了http.Dir()


例如:在你的例子中,做這個:http.FileServer(http.Dir("/go/src/github.com/patientplatypus/webserver/files")))),不要添加最后一個斜杠來制作它.../files/


它奏效了。它顯示了圖片,以及卷曲結果:


HTTP/2 200 

 accept-ranges: bytes

 content-type: image/png

 last-modified: Tue, 15 Oct 2019 22:27:48 GMT

 content-length: 107095


查看完整回答
反對 回復 2023-03-29
  • 4 回答
  • 0 關注
  • 223 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號