You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.4 KiB
60 lines
1.4 KiB
/* |
|
* 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/>. |
|
*/ |
|
|
|
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 |
|
} |
|
}
|
|
|