I have the following struct
package router
import (
"io"
"net/http"
"townspeech/components/i18n"
"townspeech/components/policy"
"townspeech/components/session"
"townspeech/controllers/base"
"townspeech/types"
)
type sidHandler struct {
req *http.Request
res http.ResponseWriter
handler sidFuncHandler
section string
err *types.ErrorJSON
sess *session.Sid
}
And I want to embed in another struct like:
package router
import (
"net/http"
"townspeech/types"
"townspeech/components/session"
"townspeech/controllers/base"
)
type authHandler struct {
sidHandler
handler authFuncHandler
auth *session.Auth
}
And the function, that use the authHandler struct:
func registerAuthHandler(handler authFuncHandler, section string) http.Handler {
return &authHandler{handler: handler, section: section}
}
The compiler complain:
# app/router
../../../router/funcs.go:9: unknown authHandler field 'section' in struct literal
FAIL app/test/account/validation [build failed]
As you can see, the two structs are in the same package, field section should not appear as private.
What am I doing wrong?
Embedding doesn't work with literals like that.
func registerAuthHandler(handler authFuncHandler, section string) http.Handler {
return &authHandler{
handler: handler,
sidHandler: sidHandler{section: section},
}
}
You can't refer to promoted fields in a struct literal. You have to create the embedded type, and refer to it by the type's name.
&authHandler{
sidHandler: sidHandler{section: "bar"},
handler: "foo",
}