调用方法
rs := AddJsonFormGormTag(`
type User struct{
Id int64
NameSpace string
DailyRoutine int
woNi int64
}
`)
fmt.Println(rs)
完成struct定义的方法
func AddJsonFormGormTag(in string) string {
var result string
scanner := bufio.NewScanner(strings.NewReader(in))
var oldLineTmp = ""
var lineTmp = ""
var propertyTmp = ""
var seperateArr []string
for scanner.Scan() {
oldLineTmp = scanner.Text()
lineTmp = strings.Trim(scanner.Text(), " ")
if strings.Contains(lineTmp, "{") || strings.Contains(lineTmp, "}") {
result = result + oldLineTmp + "\n"
continue
}
seperateArr = Split(lineTmp, " ")
// 接口或者父类声明不参与tag, 自带tag不参与tag
if len(seperateArr) == 1 || len(seperateArr) == 3 {
continue
}
r := UnderLine2Hump(seperateArr[0])
fmt.Println(r)
propertyTmp = HumpToUnderLine(seperateArr[0])
//propertyTmp = HumpToUnderLine(r)
oldLineTmp = r+" "+seperateArr[1]
//fmt.Println(oldLineTmp)
oldLineTmp = oldLineTmp + fmt.Sprintf(" `gorm:\"column:%s\" json:\"%s,omitempty\" form:\"%s\"`", propertyTmp, propertyTmp, propertyTmp)
result = result + oldLineTmp + "\n"
}
return result
}
// 增强型split,对 a,,,,,,,b,,c 以","进行切割成[a,b,c]
func Split(s string, sub string) []string {
var rs = make([]string, 0, 20)
tmp := ""
Split2(s, sub, &tmp, &rs)
return rs
}
// 附属于Split,可独立使用
func Split2(s string, sub string, tmp *string, rs *[]string) {
s = strings.Trim(s, sub)
if !strings.Contains(s, sub) {
*tmp = s
*rs = append(*rs, *tmp)
return
}
for i, _ := range s {
if string(s[i]) == sub {
*tmp = s[:i]
*rs = append(*rs, *tmp)
s = s[i+1:]
Split2(s, sub, tmp, rs)
return
}
}
}
// 下划线转驼峰
func UnderLine2Hump(s string) string {
r := ""
s = compressStr(s)
b := strings.Split(s,"_")
for _, s2 := range b {
if s2[0] >= 97 && s2[0] <= 122 {
r += strings.ToUpper(string(s2[0]))+s2[1:]
}else {
r += s2
}
}
return r
}
// 驼峰转下划线
func HumpToUnderLine(s string) string {
if s == "ID" {
return "id"
}
var rs string
elements := FindUpperElement(s)
for _, e := range elements {
s = strings.Replace(s, e, "_"+strings.ToLower(e), -1)
}
rs = strings.Trim(s, " ")
rs = strings.Trim(rs, "\t")
return strings.Trim(rs, "_")
}
// 找到字符串中大写字母的列表,附属于HumpToUnderLine
func FindUpperElement(s string) []string {
var rs = make([]string, 0, 10)
for i := range s {
if s[i] >= 65 && s[i] <= 90 {
rs = append(rs, string(s[i]))
}
}
return rs
}
func compressStr(str string) string {
if str == "" {
return ""
}
//匹配一个或多个空白符的正则表达式
reg := regexp.MustCompile("\\s+")
return reg.ReplaceAllString(str, "")
}
网友评论