File: jwk_struct_field_example_test.go

package info (click to toggle)
golang-github-lestrrat-go-jwx 2.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,872 kB
  • sloc: sh: 222; makefile: 86; perl: 62
file content (56 lines) | stat: -rw-r--r-- 1,400 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package examples_test

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/lestrrat-go/jwx/v2/jwk"
)

type Container struct {
	Key jwk.Key `json:"key"`
}

// This is only one way to parse a struct field whose dynamic
// type is unknown at compile time. In this example we use
// a proxy/wrapper to trick `Container` from attempting to
// parse the `.Key` field, and intercept the value that
// would have gone into the `Container` struct into
// `Proxy` struct's `.Key` struct field
type Proxy struct {
	Container
	Key json.RawMessage `json:"key"`
}

func Example_jwk_struct_field() {
	const src = `{
    "key": {
      "kty":"EC",
      "crv":"P-256",
      "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
      "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
      "use":"enc",
      "kid":"1"
	  }
  }`

	var p Proxy
	if err := json.Unmarshal([]byte(src), &p); err != nil {
		fmt.Printf("failed to unmarshal from JSON: %s\n", err)
		return
	}

	// Parse the intercepted `Proxy.Key` as a `jwk.Key`
	// and assign it to `Container.Key`
	key, err := jwk.ParseKey(p.Key)
	if err != nil {
		fmt.Printf("failed to parse key: %s\n", err)
		return
	}
	p.Container.Key = key

	json.NewEncoder(os.Stdout).Encode(p.Container)
	// OUTPUT:
	// {"key":{"crv":"P-256","kid":"1","kty":"EC","use":"enc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}}
}