如何使用虚拟主机在GO中使用Virtual Hosts功能性服务器静态文件

发布于 2025-02-07 08:30:57 字数 858 浏览 2 评论 0原文

如何使用GO中虚拟主机的服务器静态文件(使用fileserver)?

如果我有自己的处理程序功能,那么该任务似乎很容易解决[ 1 < /a>]:

package main

import (
    "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/")))

是行不通的 - 只是被忽略了。

我在做什么错? 这种方法通常是错误的吗?

How can I server static files (with FileServer) for a virtual host in Go?

If I have my own handler function, the task seems to be easily solvable [1]:

package main

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

But what if I need to serve static files (with FileServer)
for a virtual host?

This

r.PathPrefix("qa.example.com/").Handler(http.FileServer(http.Dir("/static/qa/")))

does not work — it is just ignored.

What am I doing wrong?
Is this approach generally wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

中二柚 2025-02-14 08:30:57
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“主机:my.example.com” 127.0.0.1:8080/static/01.go01.go重新静态文件名。

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

run test exec command curl -H "Host: my.example.com" 127.0.0.1:8080/static/01.go, 01.go replacte your static filename.

鸠魁 2025-02-14 08:30:57

注册主机/路径的处理程序。仅在调用文件处理程序时才剥离/path零件。

此注册为QA.example.com/static/*提供的文件提供了文件./ static/QA/

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

Register a handler for host/path. Strip the /path part only when invoking the file handler.

This registration serves files for qa.example.com/static/* from the directory ./static/qa/.

http.HandleFunc("qa.example.com/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./static/qa/")))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文