wiki/id.go

61 lines
1.4 KiB
Go
Raw Normal View History

2021-08-07 17:13:10 +00:00
/*
* Wiki - A wiki with editor
* Copyright (c) 2021 Peter Stuifzand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
2021-01-17 13:22:45 +00:00
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
}
}