github.com/yunabe/lgo@v0.0.0-20190709125917-42c42d410fdf/cmd/runner/sessid.go (about) 1 package runner 2 3 import ( 4 "encoding/hex" 5 "encoding/json" 6 "fmt" 7 "strings" 8 "time" 9 ) 10 11 const idPrefix = "sess" 12 13 type SessionID struct { 14 Time int64 `json:"time"` 15 } 16 17 func NewSessionID() *SessionID { 18 return &SessionID{time.Now().UnixNano()} 19 } 20 21 func (s *SessionID) Marshal() string { 22 b, err := json.Marshal(s) 23 if err != nil { 24 panic(fmt.Errorf("Unexpected error: %v", err)) 25 } 26 h := make([]byte, hex.EncodedLen(len(b))) 27 hex.Encode(h, b) 28 return idPrefix + string(h) 29 } 30 31 func (s *SessionID) Unmarshal(h string) error { 32 if !strings.HasPrefix(h, idPrefix) { 33 return fmt.Errorf("Expected %s prefix but got %s", idPrefix, h) 34 } 35 h = h[len(idPrefix):] 36 b := make([]byte, hex.DecodedLen(len(h))) 37 if _, err := hex.Decode(b, []byte(h)); err != nil { 38 return err 39 } 40 return json.Unmarshal(b, s) 41 }