forked from tangled.org/core
Monorepo for Tangled

appview: state/userutil: simplify using strings.Replace

anirudh.fi 0b8c2d96 f2bd439e

verified
Changed files
+11 -22
appview
state
userutil
+11 -22
appview/state/userutil/userutil.go
··· 16 16 return s 17 17 } 18 18 19 - parts := strings.SplitN(s[4:], "-", 2) // Skip "did-" prefix and split on first "-" 20 - if len(parts) != 2 { 21 - return s 22 - } 23 - 24 - return "did:" + parts[0] + ":" + parts[1] 19 + return strings.Replace(s, "-", ":", 2) 25 20 } 26 21 27 22 // IsFlattenedDid checks if the given string is a flattened DID. ··· 31 26 return false 32 27 } 33 28 34 - // Split the string to extract method and identifier 35 - parts := strings.SplitN(s[4:], "-", 2) // Skip "did-" prefix and split on first "-" 36 - if len(parts) != 2 { 37 - return false 38 - } 39 - 40 - // Reconstruct as a standard DID format 29 + // Reconstruct as a standard DID format using Replace 41 30 // Example: "did-plc-xyz-abc" becomes "did:plc:xyz-abc" 42 - reconstructed := "did:" + parts[0] + ":" + parts[1] 31 + reconstructed := strings.Replace(s, "-", ":", 2) 43 32 re := regexp.MustCompile(`^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$`) 44 33 45 34 return re.MatchString(reconstructed) ··· 49 38 // A flattened DID is a DID with the :s swapped to -s to satisfy certain 50 39 // application requirements, such as Go module naming conventions. 51 40 func FlattenDid(s string) string { 52 - if !IsFlattenedDid(s) { 53 - return s 54 - } 55 - 56 - parts := strings.SplitN(s[4:], ":", 2) // Skip "did:" prefix and split on first ":" 57 - if len(parts) != 2 { 58 - return s 41 + if IsDid(s) { 42 + return strings.Replace(s, ":", "-", 2) 59 43 } 44 + return s 45 + } 60 46 61 - return "did-" + parts[0] + "-" + parts[1] 47 + // IsDid checks if the given string is a standard DID. 48 + func IsDid(s string) bool { 49 + re := regexp.MustCompile(`^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$`) 50 + return re.MatchString(s) 62 51 }