为了账号安全,请及时绑定邮箱和手机立即绑定

如果从“/”加载,则不会加载 css 文件

如果从“/”加载,则不会加载 css 文件

Go
繁星点点滴滴 2022-10-04 16:51:39
我找到了一个解决方案,但它只有在指定路径时才有效fileServer := http.FileServer(http.Dir("./html"))http.Handle("/html/", http.StripPrefix("/html/", fileServer))当我尝试从“/”中执行此操作时,没有任何内容,包括http.handle("/", http.FileServer(http.Dir("./html/")))
查看完整描述

1 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

请您亲自查看,下面的程序将测试这两种情况。


package main


import (

    "bytes"

    "fmt"

    "io"

    "net/http"

    "os"

    "text/tabwriter"

    "time"

)


func main() {

    srv1 := &http.Server{

        Addr: "localhost:9090",

    }

    go func() {

        mux := http.NewServeMux()

        fileServer := http.FileServer(http.Dir("./html"))

        mux.Handle("/", fileServer)

        srv1.Handler = mux

        srv1.ListenAndServe()

    }()

    srv2 := &http.Server{

        Addr: "localhost:9091",

    }

    go func() {

        mux := http.NewServeMux()

        fileServer := http.FileServer(http.Dir("./html"))

        mux.Handle("/html/", http.StripPrefix("/html/", fileServer))

        srv2.Handler = mux

        srv2.ListenAndServe()

    }()


    srvs := []*http.Server{srv1, srv2}


    urls := []string{

        "http://%v/index.css",

        "http://%v/html/index.css",

    }


    // u := fmt.Sprintf("http://%v/html/index.css", srv.Addr)

    w := new(tabwriter.Writer)

    w.Init(os.Stdout, 8, 8, 0, '\t', 0)


    defer fmt.Println()

    defer w.Flush()


    fmt.Fprintf(w, "\n %s\t%s\t", "URL", "Response")

    fmt.Fprintf(w, "\n %s\t%s\t", "----", "----")


    for _, srv := range srvs {

        for _, f := range urls {

            <-time.After(time.Millisecond * 200)

            u := fmt.Sprintf(f, srv.Addr)

            res, err := http.Get(u)

            if err != nil {

                continue

            }

            var out bytes.Buffer

            io.Copy(&out, res.Body)

            res.Body.Close()

            fmt.Fprintf(w, "\n %s\t%s\t", u, fmt.Sprintf("%q", out.String()))

        }

    }

}

它输出


$ go run .


 URL                                    Response        

 ----                                   ----            

 http://localhost:9090/index.css        "OK\n"          

 http://localhost:9090/html/index.css   "404 page not found\n"  

 http://localhost:9091/index.css        "404 page not found\n"  

 http://localhost:9091/html/index.css   "OK\n"

它的工作原理是手动创建两个侦听不同本地地址的 HTTP 服务器。每个服务器都有不同的多路复用器设置。然后它获取具有多个不同URL的两个服务器。在继续之前,将重试多次抓取,直到没有发生错误来解释未同步的服务器启动。输出是在 TabWriter 的帮助下格式化的。


查看完整回答
反对 回复 2022-10-04
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信