Home > database >  Go - Convert raw byte string into uuid
Go - Convert raw byte string into uuid

Time:06-13

I am trying to convert raw byte strings into UUIDs in my program as follows:

Case1:

package main

import (
    "fmt"
    "strconv"

    "github.com/google/uuid"
)

func main() {
    s := `"\220\254\0021\265\235O~\244\326\216\"\227c\245\002"`
    s2, err := strconv.Unquote(s)
    if err != nil {
        panic(err)
    }

    by := []byte(s2)
    u, err := uuid.FromBytes(by)
    if err != nil {
        panic(err)
    }
    fmt.Println(u.String())
}

output:

90ac0231-b59d-4f7e-a4d6-8e229763a502

Case2:

package main

import (
    "fmt"
    "strconv"

    "github.com/google/uuid"
)

func main() {
    s := `"\235\273\'\021\003\261@\022\226\275o\265\322\002\211\263"`
    s2, err := strconv.Unquote(s)
    if err != nil {
        panic(err)
    }

    by := []byte(s2)
    u, err := uuid.FromBytes(by)
    if err != nil {
        panic(err)
    }
    fmt.Println(u.String())
}

output:

panic: invalid syntax

goroutine 1 [running]:
main.main()
    /tmp/sandbox1756881518/prog.go:14  0x149

Program exited.

The above program is working with string "\220\254\0021\265\235O~\244\326\216\"\227c\245\002" but fails at converting string "\235\273\'\021\003\261@\022\226\275o\265\322\002\211\263" into uuid. How can I convert these strings into UUIDs?

CodePudding user response:

If fails because of \'. When using backticks, all backslashes are literally backslashes and not escape sequences, so you are passing raw backslash \, followed by single quote ' to the strconv.Unquote. It causes invalid syntax. There are two workarounds here:

First

Just replace this line:

s := `"\235\273\'\021\003\261@\022\226\275o\265\322\002\211\263"`

with this:

s := `"\235\273'\021\003\261@\022\226\275o\265\322\002\211\263"`

So there is ' not \'. But if you need to programmatically convert the string, use the second approach.

Second

Import "strings":

import (
    "fmt"
    "strconv"
    "strings"
    "github.com/google/uuid"
)

And replace \' with ':

s = strings.ReplaceAll(s, `\'`, `'`)

So the full code looks like this now:

package main

import (
    "fmt"
    "strconv"
    "strings"
    "github.com/google/uuid"
)

func main() {
    s := `"\235\273\'\021\003\261@\022\226\275o\265\322\002\211\263"`
    s = strings.ReplaceAll(s, `\'`, `'`)
    s2, err := strconv.Unquote(s)
    if err != nil {
        fmt.Println(err)
    }

    by := []byte(s2)
    u, err := uuid.FromBytes(by)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(u.String())
}
  • Related