0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Golang】ユニークなID作成

Posted at

概要

Golangで、以下のような文字列であるユニークなIDの作成方法を示す。ユーザーIDの作成などに、使用する目的でプログラムを作成した。
作成には、oklog/ulidというgolangのライブラリを使用した。

0000XSNJG0MQJHBF4R33AHWHGX

Git: k-washi/bss-utils/uniquegenerator

プログラム

以下のプログラムのように時間に依存したユニークなIDを作成している。また、Validationも作成している。

package uniquegenerator

import (
	"errors"
	"math/rand"

	"github.com/oklog/ulid/v2"

	"time"
)

var (
	t       = time.Unix(1000000, 0)
	entropy = ulid.Monotonic(rand.New(rand.NewSource(t.UnixNano())), 0)
)

//generateUlid ex. output: 0000XSNJG0MQJHBF4QX1EFD6Y3
func generateUlid() ulid.ULID {
	return ulid.MustNew(ulid.Timestamp(t), entropy)
}

//Get ex. output: 0000XSNJG0MQJHBF4QX1EFD6Y3
func Get() string {
	return generateUlid().String()
}

//Validation ulid string check size
func Validation(id string) error {
	if len(id) != ulid.EncodedSize {
		return errors.New("Unique ID generator validation error: length is not match")
	}
	return nil
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?