Fork of github.com/did-method-plc/did-method-plc
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8)
9
10type VerificationMethod struct {
11 Id string `json:"id"`
12 Type string `json:"type"`
13 Controller string `json:"controller"`
14 PublicKeyMultibase string `json:"publicKeyMultibase"`
15}
16
17type DidService struct {
18 Id string `json:"id"`
19 Type string `json:"type"`
20 ServiceEndpoint string `json:"serviceEndpoint"`
21}
22
23type DidDoc struct {
24 AlsoKnownAs []string `json:"alsoKnownAs"`
25 VerificationMethod []VerificationMethod `json:"verificationMethod"`
26 Service []DidService `json:"service"`
27}
28
29type ResolutionResult struct {
30 Doc *DidDoc
31 DocJson *string
32 StatusCode int
33}
34
35func ResolveDidPlc(client *http.Client, plc_host, did string) (*ResolutionResult, error) {
36 result := ResolutionResult{}
37 res, err := client.Get(fmt.Sprintf("%s/%s", plc_host, did))
38 if err != nil {
39 return nil, fmt.Errorf("error making http request: %v", err)
40 }
41 defer res.Body.Close()
42 log.Debugf("PLC resolution result status=%d did=%s", res.StatusCode, did)
43
44 result.StatusCode = res.StatusCode
45 if res.StatusCode == 404 || res.StatusCode == 410 {
46 return &result, nil
47 } else if res.StatusCode != 200 {
48 return &result, nil
49 }
50
51 respBytes, err := io.ReadAll(res.Body)
52 if err != nil {
53 return nil, fmt.Errorf("failed to read PLC result body: %v", err)
54 }
55
56 doc := DidDoc{}
57 err = json.Unmarshal(respBytes, &doc)
58 if err != nil {
59 return nil, fmt.Errorf("failed to parse DID Document JSON: %v", err)
60 }
61 result.Doc = &doc
62
63 // parse and re-serialize JSON in pretty (indent) style
64 var data map[string]interface{}
65 err = json.Unmarshal(respBytes, &data)
66 if err != nil {
67 return nil, fmt.Errorf("failed to parse DID Document JSON: %v", err)
68 }
69 indentJson, err := json.MarshalIndent(data, "", " ")
70 if err != nil {
71 return nil, fmt.Errorf("failed to parse DID Document JSON: %v", err)
72 }
73 s := string(indentJson)
74 result.DocJson = &s
75
76 return &result, nil
77}