Skip to content

Instantly share code, notes, and snippets.

@schrierc
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schrierc/7e3a73db7636d4bdc1a8 to your computer and use it in GitHub Desktop.
Save schrierc/7e3a73db7636d4bdc1a8 to your computer and use it in GitHub Desktop.
Go JSON emtpy pointer expiriment
// Example Go JSON where marshalling includes the field only if a value
// has been set. To acheive this, use pointers for everything.
//
// This is important when interacting with some APIs since the zero value
// from Go may not be what we want to set. (Ex: 0 for int32)
package main
import (
"encoding/json"
"fmt"
)
type ModifyClusterRequest struct {
// FileStorageDir comment...
FileStorageDir *string `json:"file_storage_dir,omitempty"`
CandidatePoolSize *int32 `json:"candidate_pool_size,omitempty"`
BlacklistedOS []string `json:"blacklisted_os,omitempty"`
}
func main() {
req := ModifyClusterRequest{
CandidatePoolSize: makeInt32(42),
}
body, err := json.Marshal(&req)
if err != nil {
fmt.Println("oh dear, an error:", err)
} else {
fmt.Println("To JSON:", string(body))
}
req2 := &ModifyClusterRequest{}
if err = json.Unmarshal(body, req2); err != nil {
fmt.Println("oh dear, an error:", err)
}
fmt.Printf("Req2: %+v\n", req2)
fmt.Println("Req2 CandidatePoolSize:", *req2.CandidatePoolSize)
}
func makeString(s string) *string { return &s }
func makeInt32(n int32) *int32 { return &n }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment