-
Notifications
You must be signed in to change notification settings - Fork 175
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
Unable to handle nil pointers when implementing Encoder #46
Comments
Could you not just use a pointer to your custom type to allow for the same kind of nil checking? For example, the following works as I would expect, and I think as you're describing: package main
import (
"fmt"
"net/url"
"github.com/google/go-querystring/query"
)
type T int
func (t T) EncodeValues(key string, v *url.Values) error {
v.Add(key, fmt.Sprintf("_%d_", t))
return nil
}
type options struct {
*T `url:"t,omitempty"`
}
func main() {
v, _ := query.Values(options{})
fmt.Println(v.Encode()) // will output: ""
v, _ = query.Values(options{T: new(T)})
fmt.Println(v.Encode()) // will output: "t=_0_"
} If that doesn't work for you, could you share a code snippet of what you're trying to do? |
oh, the other thing you can do is implement the |
Sorry I wasn't clear enough. Was trying to do something like this https://play.golang.org/p/wnzO0oIJI5i package main
import (
"fmt"
"net/url"
"github.com/google/go-querystring/query"
)
type T int
// EncodeValues encodes a 0 as false, 1 as true, and nil as unknown
func (t *T) EncodeValues(key string, v *url.Values) error {
if t == nil {
v.Add(key, "unknown")
return nil
}
if *t == 0 {
v.Add(key, "false")
return nil
}
if *t == 1 {
v.Add(key, "true")
return nil
}
return fmt.Errorf("value not supported")
}
type options struct {
*T `url:"t"`
}
func main() {
v, _ := query.Values(options{})
fmt.Println(v.Encode()) // will output: false, expected unknown
} |
Got it, that makes sense. That will definitely take a little bit of work to try and make it possible. I tried a naive approach, and keep running into places throughout the package that chokes on nil values because it assumes it gets handled earlier :) |
Yeah, scratch that (I think) |
many of these values are not actually what we want, but allows us to see the change in behavior in a future change. Related to #46
I'm actually trying to do the opposite to the examples you added into the tests. I'm trying to convert a bool I'm having an issue with a non-pointer (e.g. Here's an example of what I'm trying:
Not sure if you're able to offer any guidance on how best to achieve this. Thanks. |
With the default decoding, a nil pointer is encoded as an empty string (unless omitempty was specified) so a nil *int will encode to an empty string. But when implementing a custom encoder, there is no way to check if value was nil as the value will be initialized to the zero value before EncodeValues is called.
The text was updated successfully, but these errors were encountered: