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

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

在 Go 中使用自定義 http.Handler 時為什么要使用指針?

在 Go 中使用自定義 http.Handler 時為什么要使用指針?

Go
慕森卡 2023-06-26 16:38:18
當調用http.Handle()下面的代碼片段時,我使用自己的templateHandler類型來實現該http.Handler接口。package mainimport (    "html/template"    "log"    "net/http"    "path/filepath"    "sync")type templateHandler struct {    once     sync.Once    filename string    templ    *template.Template}func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {    t.once.Do(func() {        t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))    })    t.templ.Execute(w, nil)}func main() {    http.Handle("/", &templateHandler{filename: "chat.html"})    if err := http.ListenAndServe(":8080", nil); err != nil {        log.Fatal("ListenAndServe: ", err)    }}現在由于某種原因我必須傳遞一個指向http.Handle()using的指針&templateHandler{filename: "chat.html"}。如果沒有,&我會收到以下錯誤:cannot use (templateHandler literal) (value of type templateHandler) as http.Handler value in argument to http.Handle: missing method ServeHTTP究竟為什么會發生這種情況?在這種情況下使用指針有什么區別?指針去方法界面
查看完整描述

1 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

http.Handle()需要一個實現 的值(任何值)http.Handler,這意味著它必須有一個ServeHTTP()方法。

您為該templateHandler.ServeHTTP()方法使用了指針接收器,這意味著只有指針值才有templateHandler此方法,而不是非指針templateHandler類型的指針值。

規格: 方法集:

類型可以具有與其關聯的方法集。接口類型的方法集就是它的接口。任何其他類型的方法集由使用接收者類型聲明的T所有方法T組成。對應指針類型?的方法集是用receiver或*T聲明的所有方法的集合(即還包含 的方法集)。*TTT

非指針類型僅具有帶有非指針接收器的方法。指針類型具有帶有指針和非指針接收器的方法。

您的ServeHTTP()方法修改了接收者,因此它必須是一個指針。但如果其他處理程序不需要,則ServeHTTP()可以使用非指針接收器創建該方法,在這種情況下,您可以使用非指針值作為http.Handler,如下例所示:

type myhandler struct{}


func (m myhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}


func main() {

? ? // non-pointer struct value implements http.Handler:

? ? http.Handle("/", myhandler{})

}


查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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