gpt4 book ai didi

http - Golang RedirectHandler() 返回接口(interface),以 *http.redirectHandler 结尾

转载 作者:行者123 更新时间:2023-12-01 22:33:28 24 4
gpt4 key购买 nike

请不要对我的帖子咄咄逼人,我正在努力学习 Go,但在我的理解上面临一些挑战。
这是我的示例代码:

package main

import (
"log"
"net/http"
"reflect"
"fmt"
)

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

rh := http.RedirectHandler("http://example.org", 307)
fmt.Println("The type of the object, returned by the RedirectHandler is")
fmt.Println(reflect.TypeOf(rh))
fmt.Println("End with type observation")
mux.Handle("/foo", rh)

log.Println("Listening ...")
http.ListenAndServe(":3000", mux)
}
我的问题是:
  • RedirectHandler 返回一个 Handler 接口(interface),这是一种常见的模式,有什么好处?
  • 这是否意味着您应该在函数内部有一个实现该接口(interface)然后返回该结构的结构?如果不是,我们究竟如何返回一个接口(interface),因为它本质上只是一组未实现的方法?
  • 如果你运行我的代码,你会看到变量'rh'的类型是*http.redirectHandler。对于这样的指针,我无法在 http 包中找到任何内容,因此我们从“返回接口(interface)”开始,以“这是您的指针,文档中不存在”结束。
  • 这些只是我令人困惑的想法,我会感谢那些想帮助我解决困惑的评论。
  • 最佳答案

    1. RedirectHandler returns a Handler interface, is this a common pattern and what is the benefit?

    虽然有一个经验法则是返回具体类型而不是接口(interface)(通常称为“接受接口(interface)返回结构”),但出于各种原因,有时需要隐藏实现。其中之一是可以在包的 future 版本中以任何方式自由更改实现。另一个是防止误用返回值;例如,同时访问结构字段。
    使所有这些函数(RedirectHandler、NotFoundHandler、TimeoutHandler 等)返回 http.Handler 也使它们在文档中很容易被发现:它们都作为 http.Handler 的构造函数一起出现,而不是分散在函数列表中。我假设(!)在决定这样做时可能起到了作用,但你必须问作者(你可以在 the mailing list 上这样做)。
    1. Does that mean that [RedirectHandler returns] a struct that implements that interface?

    也许。它还可以返回任何其他实现该接口(interface)的类型,尽管它确实是 Go 1.15 中的结构类型。但这可能会改变,正是因为该函数返回一个接口(interface)而不是具体类型。
    1. If you run my code, you would see that the type of the variable 'rh' is *http.redirectHandler. For such a pointer I am not able to find anything in the http package.

    默认情况下不呈现未导出标识符的文档(因为无论如何您都不能使用它们)。添加 m=all到查询字符串以显示它们: https://golang.org/pkg/net/http/?m=all#redirectHandler

    关于http - Golang RedirectHandler() 返回接口(interface),以 *http.redirectHandler 结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63790220/

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