43 lines
673 B
Go
43 lines
673 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"math/rand"
|
||
|
"strconv"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type ID struct {
|
||
|
StrID string
|
||
|
WasInt bool
|
||
|
}
|
||
|
|
||
|
func (id *ID) UnmarshalJSON(data []byte) error {
|
||
|
var intID int
|
||
|
err := json.Unmarshal(data, &intID)
|
||
|
if err == nil {
|
||
|
*id = ID{strconv.FormatInt(int64(intID), 10), true}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
var strID string
|
||
|
err = json.Unmarshal(data, &strID)
|
||
|
if err == nil {
|
||
|
*id = ID{strID, false}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
return fmt.Errorf("could not unmarshal %q as an int or string", data)
|
||
|
}
|
||
|
|
||
|
func (id *ID) NewID() string {
|
||
|
if id.WasInt {
|
||
|
l := time.Now().UnixNano()
|
||
|
r := rand.Uint64()
|
||
|
return fmt.Sprintf("_%d_%d", l, r)
|
||
|
} else {
|
||
|
return id.StrID
|
||
|
}
|
||
|
}
|