go - 如何读取 Go 中的嵌入式字段?

标签 go

我设计了一个新的Request结构,但是在某些场景下(http.Redirect),我需要获取来源http.Request

我的请求结构:

type Request struct {
    *http.Request
}

func (r *Request) IsGet() bool {
    return strings.EqualFold("GET", r.Method)
}

主要功能:

    req := http.Request{
        Method:"POST",
    }

    myReq := &Request{&req}

    // How to get original request.
    originalReq, ok := (interface{}(*myReq)).(http.Request);
    if ok {
        fmt.Printf("Method: %s\n", originalReq.Method)
    } else {
        fmt.Println("Failure")
    }

最佳答案

让我们看看是什么the language specification说:

The unqualified type name acts as the field name.

// A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4
struct {
  T1        // field name is T1
  *T2       // field name is T2
  P.T3      // field name is T3
  *P.T4     // field name is T4
  x, y int  // field names are x and y
}

myReq.Request

关于go - 如何读取 Go 中的嵌入式字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37917109/

相关文章:

go - 在命令行上使用 Go,如何隐藏来自用户终端的命令行输入?

go - 使用三重 DES 加密创建 RSA 私钥

heroku - 将 go webapps 部署到 heroku : can't find package issue

html - 如何在 Golang 模板中打印新行?

angular - 将 Angular 表单提交到 Go API 不断发布 Nil

go - 检查结构中的每个项目是否未更改

html - Golang 保存到 json 文件

windows - GAE 转到 Windows - "Cannot run program", "is not a valid Win32 application"

go - 当作为参数传递给单独包中的函数时,结构不是类型

sorting - 根据值的出现次数对 slice 进行排序