pki/vendor/xorm.io/xorm/caches/encode.go

66 lines
1.3 KiB
Go
Raw Normal View History

2020-11-25 20:36:07 +01:00
// Copyright 2020 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package caches
import (
"bytes"
"crypto/md5"
"encoding/gob"
"encoding/json"
"fmt"
"io"
)
2021-08-30 20:04:15 +02:00
// Md5 return md5 hash string
2020-11-25 20:36:07 +01:00
func Md5(str string) string {
m := md5.New()
2022-11-02 17:49:03 +01:00
_, _ = io.WriteString(m, str)
2020-11-25 20:36:07 +01:00
return fmt.Sprintf("%x", m.Sum(nil))
}
2021-08-30 20:04:15 +02:00
// Encode Encode data
2020-11-25 20:36:07 +01:00
func Encode(data interface{}) ([]byte, error) {
2022-11-02 17:49:03 +01:00
// return JsonEncode(data)
2020-11-25 20:36:07 +01:00
return GobEncode(data)
}
2021-08-30 20:04:15 +02:00
// Decode decode data
2020-11-25 20:36:07 +01:00
func Decode(data []byte, to interface{}) error {
2022-11-02 17:49:03 +01:00
// return JsonDecode(data, to)
2020-11-25 20:36:07 +01:00
return GobDecode(data, to)
}
2021-08-30 20:04:15 +02:00
// GobEncode encode data with gob
2020-11-25 20:36:07 +01:00
func GobEncode(data interface{}) ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(&data)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
2021-08-30 20:04:15 +02:00
// GobDecode decode data with gob
2020-11-25 20:36:07 +01:00
func GobDecode(data []byte, to interface{}) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
return dec.Decode(to)
}
2021-08-30 20:04:15 +02:00
// JsonEncode encode data with json
2020-11-25 20:36:07 +01:00
func JsonEncode(data interface{}) ([]byte, error) {
val, err := json.Marshal(data)
if err != nil {
return nil, err
}
return val, nil
}
2021-08-30 20:04:15 +02:00
// JsonDecode decode data with json
2020-11-25 20:36:07 +01:00
func JsonDecode(data []byte, to interface{}) error {
return json.Unmarshal(data, to)
}