Struct Don';我不懂围棋的作文
在下面的示例中,我将Struct Don';我不懂围棋的作文,struct,interface,go,composition,Struct,Interface,Go,Composition,在下面的示例中,我将http.ResponseWriter嵌入到自己的名为Response的结构中。我还添加了一个名为Status的额外字段。为什么我不能从根处理函数中访问该字段 当我在我的根处理函数中打印出w类型时,它表示它是main.Response类型,这似乎是正确的,当我打印出结构的值时,我可以看到Status存在。为什么我不能通过访问w.Status 这是stdout的内容: main.Response {ResponseWriter:0xc2080440a0 Status:0} 代
http.ResponseWriter
嵌入到自己的名为Response
的结构中。我还添加了一个名为Status
的额外字段。为什么我不能从根处理函数中访问该字段
当我在我的根处理函数中打印出w
类型时,它表示它是main.Response
类型,这似乎是正确的,当我打印出结构的值时,我可以看到Status
存在。为什么我不能通过访问w.Status
这是stdout的内容:
main.Response
{ResponseWriter:0xc2080440a0 Status:0}
代码:
主程序包
进口(
“fmt”
“反映”
“net/http”
)
类型响应结构{
http.ResponseWriter
状态int
}
func(r响应)写入头(n int){
r、 状态=n
r、 负责人(n)
}
func中间件(hhttp.Handler)http.Handler{
返回http.HandlerFunc(func(w http.ResponseWriter,r*http.Request){
resp:=响应{ResponseWriter:w}
h、 ServeHTTP(resp,r)
})
}
func root(w http.ResponseWriter,r*http.Request){
w、 写入([]字节(“根”))
fmt.Println(反射类型(w))
格式打印F(“%+v\n”,w)
fmt.Println(w.Status)/w
是http类型的变量。ResponseWriter
ResponseWriter
没有字段或方法Status
,只有您的Response
类型
http.ResponseWriter
是一种接口类型,由于您的Response
类型实现了它(因为它嵌入了ResponseWriter
),因此w
变量可能包含一个动态类型的值Response
(在您的情况下,它确实如此)
但要访问Response.Status
字段,必须将其转换为Response
类型的值
如果响应,ok:=w(响应);ok{
//resp为响应类型,您可以访问其状态字段
fmt打印LN(各自状态)//
package main
import (
"fmt"
"reflect"
"net/http"
)
type Response struct {
http.ResponseWriter
Status int
}
func (r Response) WriteHeader(n int) {
r.Status = n
r.ResponseWriter.WriteHeader(n)
}
func middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
resp := Response{ResponseWriter: w}
h.ServeHTTP(resp, r)
})
}
func root(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("root"))
fmt.Println(reflect.TypeOf(w))
fmt.Printf("%+v\n", w)
fmt.Println(w.Status) // <--- This causes an error.
}
func main() {
http.Handle("/", middleware(http.HandlerFunc(root)))
http.ListenAndServe(":8000", nil)
}
if resp, ok := w.(Response); ok {
// resp is of type Response, you can access its Status field
fmt.Println(resp.Status) // <--- properly prints status
}