q5/strutils.go
aozhiwei 5c996e016a 1
2024-06-29 14:57:15 +08:00

145 lines
2.5 KiB
Go

package q5
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"encoding/json"
"hash/crc32"
"io"
"strings"
)
const (
JSON_NONE = 0
JSON_ARRAY = iota
JSON_OBJECT = iota
)
func Md5Str(data string) string {
h := md5.New()
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
func Base64Encode(data string) string {
strbytes := []byte(data)
encoded := base64.StdEncoding.EncodeToString(strbytes)
return encoded
}
func Base64Decode(data string) (string, error) {
decoded, err := base64.StdEncoding.DecodeString(data)
return string(decoded), err
}
func Crc32(data string) uint32 {
ieee := crc32.NewIEEE()
io.WriteString(ieee, data)
code := ieee.Sum32()
return code
}
func JsonStrType(data string) int32 {
arrayIdx := strings.IndexByte(data, '[')
objectIdx := strings.IndexByte(data, '{')
if arrayIdx < 0 && objectIdx < 0 {
return JSON_NONE
} else {
if arrayIdx < 0 {
return JSON_OBJECT
}
if objectIdx < 0 {
return JSON_ARRAY
}
if arrayIdx < objectIdx {
return JSON_ARRAY
} else {
return JSON_OBJECT
}
}
}
func EncodeJson(p interface{}) string {
if jsonBytes, err := json.Marshal(p); err == nil {
return string(jsonBytes)
} else {
return ""
}
}
func DecodeJson(data string, p interface{}) error {
err := json.Unmarshal([]byte(data), &p)
return err
}
func StrSplit(s string, sep string) []string {
return strings.Split(s, sep)
}
func StrContains(s string, substr string) bool {
return strings.Contains(s, substr)
}
func ConvertUpperCamelCase(name string) string {
newName := ""
preIs_ := false
for i := 0; i < len(name); i++ {
if i == 0 {
newName += strings.ToUpper(name[i : i+1])
preIs_ = name[i] == '_'
} else {
if preIs_ {
if name[i] != '_' {
newName += strings.ToUpper(name[i : i+1])
}
} else {
if name[i] != '_' {
newName += name[i : i+1]
}
}
preIs_ = name[i] == '_'
}
}
return newName
}
func NewEmptyStrPtr() *string {
tmpStr := ""
return &tmpStr
}
func IsPureNumber(str string) bool {
for i := 0; i < len(str); i++ {
if !(str[i] >= '0' && str[i] <= '9') {
return false
}
}
return true
}
func GenFieldKvEmptyAsNull(key string, val string) []string {
if val == "" {
return []string{"!" + key, "NULL"}
} else {
return []string{key, val}
}
}
func IsWeb3ZeroAddress(address string) bool {
return address == "0x0000000000000000000000000000000000000000"
}
func BigIntStrCmp(a string, b string) int {
if len(a) == len(b) {
return strings.Compare(a, b)
} else {
if len(a) < len(b) {
return -1
} else {
return 1
}
}
}