Skip to content

Instantly share code, notes, and snippets.

@KaiserWerk
Created September 12, 2022 20:49
Show Gist options
  • Save KaiserWerk/1360f652fd6e2ff0a95241c7bbd12822 to your computer and use it in GitHub Desktop.
Save KaiserWerk/1360f652fd6e2ff0a95241c7bbd12822 to your computer and use it in GitHub Desktop.
Custom JSON (Un)Marshaler in Go
package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
)
type Scope []string
func (s *Scope) MarshalJSON() ([]byte, error) {
if s == nil {
return nil, fmt.Errorf("scope is nil")
}
return []byte(fmt.Sprintf("%q", url.QueryEscape(strings.Join(*s, " ")))), nil
}
func (s *Scope) UnmarshalJSON(d []byte) error {
elems := make([]string, 0, 5)
err := json.Unmarshal(d, &elems)
if err != nil {
return err
}
*s = elems
return nil
}
func (s Scope) String() string {
return url.QueryEscape(strings.Join(s, " "))
}
type MyConf struct {
// just some data, like an actual config
Host string
Scope Scope
}
func main() {
cfg := MyConf{
Host: "localhost:8080",
Scope: []string{"api", "email", "profile"},
}
data, err := json.MarshalIndent(cfg, "", "\t")
handleErr(err)
fmt.Printf("%s\n", data)
cfg2 := MyConf{}
err = json.Unmarshal(data, &cfg2)
handleErr(err)
fmt.Printf("\n%+v\n", cfg2)
}
func handleErr(err error) {
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment