github.com/storacha/go-ucanto@v0.7.2/core/schema/did.go (about)

     1  package schema
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/storacha/go-ucanto/core/result/failure"
     8  	"github.com/storacha/go-ucanto/did"
     9  )
    10  
    11  type didConfig struct {
    12  	method string
    13  }
    14  
    15  type DIDOption func(*didConfig)
    16  
    17  func WithMethod(method string) DIDOption {
    18  	return func(c *didConfig) {
    19  		c.method = method
    20  	}
    21  }
    22  
    23  func DID(opts ...DIDOption) Reader[string, did.DID] {
    24  	c := &didConfig{}
    25  	for _, opt := range opts {
    26  		opt(c)
    27  	}
    28  	return reader[string, did.DID]{
    29  		readFunc: func(input string) (did.DID, failure.Failure) {
    30  			pfx := "did:"
    31  			if c.method != "" {
    32  				pfx = fmt.Sprintf("%s%s:", pfx, c.method)
    33  			}
    34  			if !strings.HasPrefix(input, pfx) {
    35  				return did.Undef, NewSchemaError(fmt.Sprintf(`Expected a "%s" but got "%s" instead`, pfx, input))
    36  			}
    37  			d, err := did.Parse(input)
    38  			if err != nil {
    39  				return did.Undef, NewSchemaError(err.Error())
    40  			}
    41  			return d, nil
    42  		},
    43  	}
    44  }
    45  
    46  // DIDString read a string that is in DID format.
    47  func DIDString(opts ...DIDOption) Reader[string, string] {
    48  	rdr := DID(opts...)
    49  	return reader[string, string]{
    50  		readFunc: func(input string) (string, failure.Failure) {
    51  			d, err := rdr.Read(input)
    52  			if err != nil {
    53  				return "", err
    54  			}
    55  			return d.String(), nil
    56  		},
    57  	}
    58  }