golang-uuid

 uuid第三方库可以在github上找,我在这使用的是:github.com/satori/go.uuid

PS:不知道哪里原因,使用go mod 管理包,下载的包和github上的不是完全一样,也特意看了版本,都是v1.2.0

生成uuid主要函数:

// NewV1 returns UUID based on current timestamp and MAC address.
func NewV1() UUID {
    return global.NewV1()
}

// NewV2 returns DCE Security UUID based on POSIX UID/GID.
func NewV2(domain byte) UUID {
    return global.NewV2(domain)
}

// NewV3 returns UUID based on MD5 hash of namespace UUID and name.
func NewV3(ns UUID, name string) UUID {
    return global.NewV3(ns, name)
}

// NewV4 returns random generated UUID.
func NewV4() UUID {
    return global.NewV4()
}

// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
func NewV5(ns UUID, name string) UUID {
    return global.NewV5(ns, name)
}

// Generator provides interface for generating UUIDs.
type Generator interface {
    NewV1() UUID
    NewV2(domain byte) UUID
    NewV3(ns UUID, name string) UUID
    NewV4() UUID
    NewV5(ns UUID, name string) UUID
}

示例:

// Creating UUID Version 4
    u1 := uuid.NewV1()
    fmt.Printf("UUIDv1: %s\n", u1)

    // Parsing UUID from string input 比如url传参,后端得到的是字符串,把字符串解析成UUID类型
    u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
    if err != nil {
        fmt.Printf("Something gone wrong: %s", err)
    }
    fmt.Printf("Successfully parsed: %s", u2)

 

如果是Linux,有专门生成UUID的命令:uuidgen

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("uuidgen").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", out)

}

uuidgen支持两个参数,-r生成随机uuid,-t生成基于时间的uuid。

out, err := exec.Command("uuidgen", "t").Output()
......

GUID扩展:https://blog.csdn.net/signjing/article/details/69358110

posted @ 2018-11-23 15:57  静静别跑  阅读(2275)  评论(1编辑  收藏  举报