MagicArray:像php一樣,讓Go業務程式碼不再卷!

阿旭^_^發表於2023-12-26

卷!一個字形容了當今碼農行業的現狀。一層一層的程式碼結構,一個一個dto,entity,vo,req,resp。這些物件越來越多,讓碼農們非常勞於奔命,加一個欄位,改一個欄位,影響面有多少。程式碼量也越來越大。有可能一個程式碼,要建10多個資料物件。這雖然有點誇張,但體現了行業的亂象。

我是曾經寫php程式碼的研發,由於php的併發能力的不足,和編譯檢錯能力不足,導致行業用php越來越少了。但是不得不說,在php的時代,跟本不需要這麼多物件,因為有一個強大的array,包羅永珍。難道我們go、java都不能也透過這種方式實現嗎?

 

MagicArray:像php一樣,讓Go業務程式碼不再卷!

 

Allright,  由此,MagicArray就誕生了,不用關心型別,不用關心空指標,不用建立哪麼多資料物件,輕鬆資料轉換。廢話不多說,上程式碼:

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},
   {"uid":2,"userName":"Lily","isMale":false}
]

 

參考:https://lingdor.medium.com/magicarray-use-to-data-translate-easily-8831b937bfc1

 

相關文章