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

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

如果從“/”加載,則不會加載 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 關注
  • 97 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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