I have a JSON struct that looks something like this in pkg/response/foobar.go
type Foo struct {
RequestID string `json:"request_id"`
Response string `json:"response"`
}
func (resp *Foo) JSONBytes() []byte {
result, err := json.Marshal(resp)
if err != nil {
// log the error (see below)
}
return result
}
I am very new to Go, and I am trying to integrate Uber's Zap logger. In pkg/endpoint/route1.go
, I have
func processRequest(s *zap.SugaredLogger, // other params) error {
for resp := range responses {
//... other cases
case *response.Foo:
resp.Sugar = s // want to do something like this
respBytes := resp.JSONBytes()
wsResponses <- respBytes
}
}
I then want to be able to pass the logger that's being used in processRequest
and make it available to use for JSONBytes()
. However, I am not sure of the implications of mixing a JSON struct with methods:
type Foo struct {
RequestID string `json:"request_id"`
Response string `json:"response"`
Sugar *zap.SugaredLogger `json:"-"`
}
where I can then use the logger in JSONBytes()
. If I try passing it as an argument in to JSONBytes(s)
, I get
resp (variable of type response.Response) cannot have dynamic type *response.Foo (wrong type for method JSONBytes (have func(s *go.uber.org/zap.SugaredLogger) []byte, want func() []byte))compilerImpossibleAssert
What is the most idiomatic way to make the logger available for JSONBytes()
.