Skip to content

Instantly share code, notes, and snippets.

@mickelsonm
Created March 6, 2014 20:27
Show Gist options
  • Save mickelsonm/9398942 to your computer and use it in GitHub Desktop.
Save mickelsonm/9398942 to your computer and use it in GitHub Desktop.
Some Guid thing I was playing around with.
package guid
import(
"crypto/rand"
"encoding/hex"
"regexp"
"strconv"
)
type Guid struct{
Hyphenated bool
Value string
}
func (g *Guid) New() string{
u := make([]byte, 16)
rand.Read(u)
u[8] = (u[8] | 0x80) & 0xBF
u[6] = (u[6] | 0x40) & 0x4F
raw := hex.EncodeToString(u)
if g.Hyphenated {
//ex. 4d23f860-80e6-4984-8e10-5b87ad86c1ff
tmp := ""
for i, c := range raw {
if i == 8 || i == 12 || i == 16 || i == 20{
tmp += "-"
}
l, _ := strconv.Unquote(strconv.QuoteRune(c))
tmp += l
}
g.Value = tmp
}else{
g.Value = raw
}
return g.Value
}
func (g *Guid) Parse(str string) error {
if len(str) == 0{
return errors.New("Invalid arguments for Guid.Parse")
}
if !IsGuid(str){
return errors.New("Invalid Guid format.")
}
g.Value = str
return nil
}
func NewGuid() string{
g := Guid{}
return g.New()
}
func NewHyphenatedGuid() string{
g := Guid{Hyphenated: true}
return g.New()
}
func IsGuid(str string) (bool, error){
return regexp.MatchString(
"^(\\{){0,1}[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}(\\}){0,1}$", str)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment