gpt4 book ai didi

go - http.HandlerFunc 如何在没有明确传递的情况下获得响应编写器和请求?

转载 作者:行者123 更新时间:2023-12-01 22:42:46 26 4
gpt4 key购买 nike

我正在学习来自 PHP/JS 背景的 Go。我遇到了一个我不太确定发生了什么的例子。怎么样timeHandler接收 http.ResponseWriter 和 http.Request 如果它们没有显式传递给函数调用?

package main

import (
"log"
"net/http"
"time"
)

func timeHandler(w http.ResponseWriter, r *http.Request) {
tm := time.Now().Format(time.RFC1123)
w.Write([]byte("The time is: " + tm))
}

func main() {
mux := http.NewServeMux()

// *** Why isn't there any undefined value errors here?
th := http.HandlerFunc(timeHandler)

mux.Handle("/time", th)

http.ListenAndServe(":8080", mux)
}

相关帖子没有足够通俗地回答这个问题。这篇文章中与 Deefdragon 的线程做得很好。总结一下:

it registers the function, without calling it until later

最佳答案

在 Go 中,函数是 first class ,这意味着它们可以分配给变量,传递给函数等。

在这种情况下,http.HandlerFunc 接受一个函数作为参数(参数为 writer 和 request),从而创建一个处理程序 th。然后将 th 传递给多路复用器。

当向时间端点发出请求时,多路复用器会寻找合适的处理程序 th。然后它执行 th。 (有时称为回调)

在 th 内部,然后回调处理函数,传递参数 w 和 r。然后执行示例中的代码

关于go - http.HandlerFunc 如何在没有明确传递的情况下获得响应编写器和请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60097863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com