mar-755-KK / pkg /tools /tools.go
aurorax-neo's picture
init
a4468f1
raw
history blame
1.21 kB
package tools
import (
jsoniter "github.com/json-iterator/go"
"os"
"os/signal"
"syscall"
)
func HandleSignals(exitCode int) int {
s := make(chan os.Signal)
signal.Notify(s, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
EXIT:
for {
switch <-s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
exitCode = 0
break EXIT
case syscall.SIGHUP:
default:
break EXIT
}
}
return exitCode
}
// Struct2Bytes 将结构体转换为字节数组
func Struct2Bytes(v interface{}) ([]byte, error) {
// 创建一个jsonIter的Encoder
configCompatibleWithStandardLibrary := jsoniter.ConfigCompatibleWithStandardLibrary
// 将结构体转换为JSON文本并保持顺序
bytes_, err := configCompatibleWithStandardLibrary.Marshal(v)
if err != nil {
return nil, err
}
return bytes_, nil
}
// Bytes2Struct 将字节数组转换为结构体
func Bytes2Struct(data []byte, v interface{}) error {
// 创建一个jsonIter的Decoder
configCompatibleWithStandardLibrary := jsoniter.ConfigCompatibleWithStandardLibrary
// 将JSON字节数组解码为结构体
err := configCompatibleWithStandardLibrary.Unmarshal(data, v)
if err != nil {
return err
}
return nil
}