gpt4 book ai didi

http.Handle(Handler 或 HandlerFunc)

转载 作者:IT王子 更新时间:2023-10-29 01:24:20 34 4
gpt4 key购买 nike

下面的功能是如何实现的?

func handle(pattern string, handler interface{}) {
// ... what goes here? ...
http.Handle(pattern, ?)
}

handle("/foo", func(w http.ResponseWriter, r http.Request) { io.WriteString(w, "foo") }
handle("/bar", BarHandler{})

handle() 被传递给匹配 http.HandlerFunc 类型的函数或实现 http.Handler 接口(interface)的类型。

最佳答案

与其诉诸反射(reflection),我会这样做:

func handle(pattern string, handler interface{}) {
var h http.Handler
switch handler := handler.(type) {
case http.Handler:
h = handler
case func(http.ResponseWriter, *http.Request):
h = http.HandlerFunc(handler)
default:
// error
}
http.Handle(pattern, h)
}

关于http.Handle(Handler 或 HandlerFunc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6365535/

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