第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

http.FileServer 只服務(wù)于 index.html

http.FileServer 只服務(wù)于 index.html

Go
達(dá)令說(shuō) 2022-04-26 15:26:56
我的簡(jiǎn)單文件服務(wù)器代碼:package mainimport (    "net/http"    "os"    "github.com/gorilla/handlers"    "github.com/gorilla/mux")func main() {    r := mux.NewRouter()    // default file handler    r.Handle("/", http.FileServer(http.Dir("web")))    // run on port 8080    if err := http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, r)); err != nil {        panic(err)    }}我的目錄結(jié)構(gòu)是:cmd/server/main.goweb/index.htmlweb/favicon.icoweb/favicon.pngweb/css/main.cssindex.html要求main.css。所以當(dāng)我運(yùn)行時(shí),go run cmd/server/main.go我得到以下輸出:127.0.0.1 - - [24/Dec/2019:22:45:26 -0X00] "GET / HTTP/1.1" 304 0127.0.0.1 - - [24/Dec/2019:22:45:26 -0X00] "GET /css/main.css HTTP/1.1" 404 19我可以看到該index.html頁(yè)面,但沒(méi)有 CSS。當(dāng)我請(qǐng)求任何其他文件(例如favicon.ico)時(shí),我也會(huì)收到 404。為什么我的FileServer唯一服務(wù)index.html?
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊

為了說(shuō)明為什么這不起作用,請(qǐng)考慮以下測(cè)試應(yīng)用程序:


package main


import (

    "fmt"

    "net/http"


    "github.com/gorilla/mux"

)


type testHandler struct{}


func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    fmt.Printf("Got request for %s\n", r.URL)

}


func main() {

    r := mux.NewRouter()

    hndlr := testHandler{}

    r.Handle("/", &hndlr)


    // run on port 8080

    if err := http.ListenAndServe(":8080", r); err != nil {

        panic(err)

    }

}

如果您http://127.0.0.1:8080/在瀏覽器中運(yùn)行并訪問(wèn)它,它將記錄Got request for /. 但是,如果您訪問(wèn) http://127.0.0.1:8080/foo,您將收到 404 錯(cuò)誤,并且不會(huì)記錄任何內(nèi)容。這是因?yàn)閞.Handle("/", &hndlr)只會(huì)匹配它,/而不是它下面的任何東西。


如果將其更改為r.PathPrefix("/").Handler(&hndlr),它將按預(yù)期工作(路由器會(huì)將所有路徑傳遞給處理程序)。因此,要將您的示例更改r.Handle("/", http.FileServer(http.Dir("web")))為r.PathPrefix("/").Handler( http.FileServer(http.Dir("web"))).


注意:因?yàn)檫@是傳遞所有路徑,F(xiàn)ileServer所以實(shí)際上不需要使用 Gorilla Mux;假設(shè)您將使用它來(lái)添加其他一些路線,我將其保留。


查看完整回答
反對(duì) 回復(fù) 2022-04-26
  • 1 回答
  • 0 關(guān)注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)