q5/strutils.go
2023-10-25 15:46:41 +08:00

102 lines
1.8 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 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
}