1
0
mirror of https://github.com/fumiama/tienyik.git synced 2026-06-30 07:50:23 +08:00

feat: add log & supporting packages

This commit is contained in:
源文雨
2025-10-30 23:23:45 +08:00
parent 617fc662c5
commit 15fcc9a338
19 changed files with 672 additions and 12 deletions

22
internal/hson/req.go Normal file
View File

@@ -0,0 +1,22 @@
package hson
import (
"bytes"
"encoding/json"
"github.com/fumiama/tienyik"
"github.com/fumiama/tienyik/internal/log"
)
func Marshal(tya *tienyik.AES, v any) []byte {
w := bytes.NewBuffer(make([]byte, 0, 1024))
err := json.NewEncoder(w).Encode(v)
if err != nil {
panic(err)
}
log.Debugln("Marshal JSON:", w.String())
if tya != nil {
return tya.Encrypt(w.Bytes())
}
return w.Bytes()
}

56
internal/hson/resp.go Normal file
View File

@@ -0,0 +1,56 @@
package hson
import (
"encoding/base64"
"encoding/json"
"errors"
"io"
"strconv"
"github.com/fumiama/tienyik"
"github.com/fumiama/tienyik/internal/log"
)
type responseBase[T any] struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data T `json:"data"`
EData string `json:"edata"`
}
func (rb *responseBase[T]) ok() error {
if rb.Code != 0 {
return errors.New("[" + strconv.Itoa(rb.Code) + "] " + rb.Msg)
}
return nil
}
func Unmarshal[T any](tya *tienyik.AES, r io.Reader) (data T, err error) {
var rsp responseBase[T]
err = json.NewDecoder(r).Decode(&rsp)
if err == nil {
err = rsp.ok()
}
if err != nil {
return
}
if len(rsp.EData) > 0 && tya != nil {
var d []byte
d, err = base64.StdEncoding.DecodeString(rsp.EData)
if err != nil {
return
}
d, err = tya.Decrypt(d)
if err != nil {
return
}
log.Debugln("decrypted data:", string(d))
err = json.Unmarshal(d, &rsp)
if err != nil {
return
}
err = rsp.ok()
}
data = rsp.Data
return
}