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

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

如何在 Go 中使用虛擬主機功能服務靜態文件

如何在 Go 中使用虛擬主機功能服務靜態文件

Go
波斯汪 2022-12-19 21:12:45
如何FileServer在 Go 中為虛擬主機提供靜態文件(帶有 )?如果我有自己的處理函數,任務似乎很容易解決 [ 1 ]:package mainimport (    "fmt"    "net/http")func main() {    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintf(w, "Hello, world!")    })    http.HandleFunc("qa.example.com/", func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintf(w, "Hello, improved world!")    })    http.ListenAndServe(":8080", nil)}但是,如果我需要為FileServer虛擬主機提供靜態文件(帶有 )怎么辦?這個r.PathPrefix("qa.example.com/").Handler(http.FileServer(http.Dir("/static/qa/")))不起作用——它只是被忽略了。我究竟做錯了什么?這種方法通常是錯誤的嗎?
查看完整描述

2 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

package main


import (

    "embed"

    "fmt"

    "net/http"

    "strings"

    "time"

)


//go:embed *.go

var f embed.FS


func main() {

    // embed.Fs defaule modtime use now or env value.

    now := time.Now()

    // use mapping host to http.FileSystem

    vhosts := make(map[string]http.FileSystem)

    vhosts["qa.example.com"] = http.FS(f)    // from embed.FS

    vhosts["my.example.com"] = http.Dir(".") // from http.Dir


    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        fmt.Fprintf(w, "Hello, world!")

    })

    http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {

        // find host

        fs, ok := vhosts[r.Host]

        if !ok {

            w.WriteHeader(404)

            w.Write([]byte("404 not found vhost"))

            return

        }

        // open file from http.FileSystem

        file, err := fs.Open(strings.TrimPrefix(r.URL.Path, "/static/"))

        if err != nil {

            // reference go1.18.3/net/http/fs.go toHTTPError function hander file error.

            w.Write([]byte("check err is 403 or 404 or 500"))

            return

        }

        stat, _ := file.Stat()

        // fix embed modtime is zero.

        modtime := stat.ModTime()

        if modtime.IsZero() {

            modtime = now

        }

        // response

        http.ServeContent(w, r, stat.Name(), modtime, file)


    })


    http.ListenAndServe(":8080", nil)

}

運行 test exec 命令curl -H "Host: my.example.com" 127.0.0.1:8080/static/01.go,01.go 替換您的靜態文件名。


查看完整回答
反對 回復 2022-12-19
?
largeQ

TA貢獻2039條經驗 獲得超8個贊

為 注冊處理程序host/path。/path僅在調用文件處理程序時剝離該部分。

此注冊為qa.example.com/static/*目錄中的文件提供服務./static/qa/。

http.HandleFunc("qa.example.com/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./static/qa/")))



查看完整回答
反對 回復 2022-12-19
  • 2 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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