MagicArray:像php一样,让Go业务代码不再卷!
卷!一个字形容了当今码农行业的现状。一层一层的代码结构,一个一个dto,entity,vo,req,resp。这些对象越来越多,让码农们非常劳于奔命,加一个字段,改一个字段,影响面有多少。代码量也越来越大。有可能一个代码,要建10多个数据对象。这虽然有点夸张,但体现了行业的乱象。
我是曾经写php代码的研发,由于php的并发能力的不足,和编译检错能力不足,导致行业用php越来越少了。但是不得不说,在php的时代,跟本不需要这么多对象,因为有一个强大的array,包罗万象。难道我们go、java都不能也通过这种方式实现吗?
Allright, 由此,MagicArray就诞生了,不用关心类型,不用关心空指针,不用创建哪么多数据对象,轻松数据转换。废话不多说,上代码:
go get github.com/lingdor/magicarray@v0.0.5
DTO替代方式:
package main import ( "encoding/json" "fmt" arr "github.com/lingdor/magicarray" "time" ) type UserDTO struct { Id int `json:"userid"` Name string } type ScoreDTO struct { Score int ScoreTime time.Time } type AreaDto struct { CityId int City string } func dtosCommand() { user := UserDTO{ Id: 1, Name: "bobby", } score := ScoreDTO{ Score: 66, ScoreTime: time.Now(), } area := AreaDto{ CityId: 10000, City: "beij", } mix, _ := arr.Merge(arr.ValueofStruct(user), score, area) mix = arr.Pick(mix, "Id", "City", "Score") if bs, err := json.Marshal(mix); err == nil { fmt.Println(string(bs)) } else { panic(err) } }
输出
{"userid":1,"City":"newyork","Score":66}
数据变换
package main import ( "encoding/json" "fmt" arr "github.com/lingdor/magicarray" ) type ColumnUserEntity struct { Id int `json:"uid"` UserName string IsMale bool } func columnCommand() { users := []ColumnUserEntity{ { Id: 1, UserName: "Bobby", IsMale: true, }, { Id: 2, UserName: "Lily", IsMale: false, }, } usersArr := arr.ValueOfSlice(users) usersArr = arr.WashColumn(usersArr, arr.WashTagRuleJsonInitialLower()) if bs, err := json.Marshal(usersArr); err == nil { fmt.Println(string(bs)) } else { panic(err) } usersArr = arr.Column(usersArr, "UserName") if bs, err := json.Marshal(usersArr); err == nil { fmt.Println(string(bs)) } else { panic(err) } }
输出
["Bobby","Lily"]
tag操作
package main import ( "encoding/json" "fmt" arr "github.com/lingdor/magicarray" ) type UserEntity struct { Id int `json:"uid"` UserName string IsMale bool } func tagCommand() { users := UserEntity{ Id: 1, UserName: "Bobby", IsMale: true, } userArr := arr.ValueofStruct(users) userArr = arr.SetTag(userArr, "Id", "json", "UserId") if bs, err := json.Marshal(userArr); err == nil { fmt.Println(string(bs)) } else { panic(err) } }
输出
{"uid":1,"UserName":"Bobby","IsMale":true,"UserId":1}
参考:https://lingdor.medium.com/magicarray-use-to-data-translate-easily-8831b937bfc1