How do I unwrap a wrapped struct in golang?

huangapple go评论141阅读模式
英文:

How do I unwrap a wrapped struct in golang?

问题

我一直在搜索,但似乎找不到如何获取Go中包装结构的后端结构的方法。

这是使用情况:我正在使用 traffic 来管理我的 Web 应用程序,它使用自己包装的 http.Request 以及其他几个结构体。声明如下:

type Request struct {
	*http.Request
}

我正在尝试集成 go-guardian,我需要将一个 http.Request 发送到以下函数:

	Authenticate(r *http.Request) (Info, error)

问题是,我如何获取 traffic.Request 所构建的 *http.Request

我记得在某个教程中看到过一种方法来做到这一点,但我一直找不到它(问题是我不确定我是否使用了正确的术语来描述包装结构)。

非常感谢您的任何反馈 - 谢谢。

英文:

So I have been searching and can't seem to find how to get the backend struct for a wrapped struct in go.

This is the use case: I am using traffic to manage my web app and it uses it's own wrapped version of the http.Request as well as several others. the declaration looks like this:

type Request struct {
	*http.Request
}

I am trying to incorporate go-guardian and I need to send an http.Request to this function:

	Authenticate(r *http.Request) (Info, error)

The question is how do I get the *http.Request that the traffic.Request was made out of?

I seem to remember seeing a way to do this in a tutorial somewhere but I haven't been able to find it (the problem is I'm not sure I'm using the right term for a wrapped struct).

Any feedback would be graetly appreciated - thank you.

答案1

得分: 1

嵌入字段可以通过其类型名称进行访问:

type Request struct {
    *http.Request
}

对于上述代码:

func f(r *Request) {
  // 这将传递嵌入的 *http.Request
  g(r.Request)
}
英文:

An embedded field can be accessed using its type name:

type Request struct {
    *http.Request
}

For the above:

func f(r *Request) {
  // This will pass the embedded *http.Request
  g(r.Request)
}


</details>



huangapple
  • 本文由 发表于 2021年6月2日 03:25:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/67794905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定