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/...運行您的應用程序的用戶可以讀取它。

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,請告訴我,我可以重構。感謝所有幫助過的人!

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

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
- 4 回答
- 0 關注
- 223 瀏覽
添加回答
舉報