convertor

package
v2.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2024 License: MIT Imports: 15 Imported by: 45

Documentation

Overview

Package convertor implements some functions to convert data.

Package convertor implements some functions to convert data.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ColorHexToRGB

func ColorHexToRGB(colorHex string) (red, green, blue int)

ColorHexToRGB convert hex color to rgb color. Play: https://go.dev/play/p/o7_ft-JCJBV

Example
colorHex := "#003366"
r, g, b := ColorHexToRGB(colorHex)

fmt.Println(r, g, b)
Output:

0 51 102

func ColorRGBToHex

func ColorRGBToHex(red, green, blue int) string

ColorRGBToHex convert rgb color to hex color. Play: https://go.dev/play/p/nzKS2Ro87J1

Example
r := 0
g := 51
b := 102
colorHex := ColorRGBToHex(r, g, b)

fmt.Println(colorHex)
Output:

#003366

func CopyProperties added in v2.1.16

func CopyProperties[T, U any](dst T, src U) error

CopyProperties copies each field from the source into the destination. It recursively copies struct pointers and interfaces that contain struct pointers. use json.Marshal/Unmarshal, so json tag should be set for fields of dst and src struct. Play: https://go.dev/play/p/oZujoB5Sgg5

Example
type Disk struct {
	Name    string  `json:"name"`
	Total   string  `json:"total"`
	Used    string  `json:"used"`
	Percent float64 `json:"percent"`
}

type DiskVO struct {
	Name    string  `json:"name"`
	Total   string  `json:"total"`
	Used    string  `json:"used"`
	Percent float64 `json:"percent"`
}

type Indicator struct {
	Id      string    `json:"id"`
	Ip      string    `json:"ip"`
	UpTime  string    `json:"upTime"`
	LoadAvg string    `json:"loadAvg"`
	Cpu     int       `json:"cpu"`
	Disk    []Disk    `json:"disk"`
	Stop    chan bool `json:"-"`
}

type IndicatorVO struct {
	Id      string   `json:"id"`
	Ip      string   `json:"ip"`
	UpTime  string   `json:"upTime"`
	LoadAvg string   `json:"loadAvg"`
	Cpu     int64    `json:"cpu"`
	Disk    []DiskVO `json:"disk"`
}

indicator := &Indicator{Id: "001", Ip: "127.0.0.1", Cpu: 1, Disk: []Disk{
	{Name: "disk-001", Total: "100", Used: "1", Percent: 10},
	{Name: "disk-002", Total: "200", Used: "1", Percent: 20},
	{Name: "disk-003", Total: "300", Used: "1", Percent: 30},
}}

indicatorVO := IndicatorVO{}

CopyProperties(&indicatorVO, indicator)

fmt.Println(indicatorVO.Id)
fmt.Println(indicatorVO.Ip)
fmt.Println(len(indicatorVO.Disk))
Output:

001
127.0.0.1
3

func DecodeByte added in v2.1.6

func DecodeByte(data []byte, target any) error

DecodeByte decode byte slice data to target object. Play: https://go.dev/play/p/zI6xsmuQRbn

Example
var obj string
byteData := []byte{6, 12, 0, 3, 97, 98, 99}
err := DecodeByte(byteData, &obj)
if err != nil {
	return
}

fmt.Println(obj)
Output:

abc

func DeepClone added in v2.1.15

func DeepClone[T any](src T) T

DeepClone creates a deep copy of passed item. can't clone unexported field of struct Play: https://go.dev/play/p/j4DP5dquxnk

Example
type Struct struct {
	Str   string
	Int   int
	Float float64
	Bool  bool
	Nil   interface{}
	// unexported string
}

cases := []interface{}{
	true,
	1,
	0.1,
	map[string]int{
		"a": 1,
		"b": 2,
	},
	&Struct{
		Str:   "test",
		Int:   1,
		Float: 0.1,
		Bool:  true,
		Nil:   nil,
		// unexported: "can't be cloned",
	},
}

for _, item := range cases {
	cloned := DeepClone(item)

	isPointerEqual := &cloned == &item
	fmt.Println(cloned, isPointerEqual)
}
Output:

true false
1 false
0.1 false
map[a:1 b:2] false
&{test 1 0.1 true <nil>} false

func EncodeByte added in v2.1.6

func EncodeByte(data any) ([]byte, error)

EncodeByte encode data to byte slice. Play: https://go.dev/play/p/DVmM1G5JfuP

Example
byteData, _ := EncodeByte("abc")
fmt.Println(byteData)
Output:

[6 12 0 3 97 98 99]

func GbkToUtf8 added in v2.2.2

func GbkToUtf8(bs []byte) ([]byte, error)

GbkToUtf8 convert GBK encoding data to utf8 encoding data. Play: https://go.dev/play/p/OphmHCN_9u8

Example
gbkData, _ := Utf8ToGbk([]byte("hello"))
utf8Data, _ := GbkToUtf8(gbkData)

fmt.Println(utf8.Valid(utf8Data))
fmt.Println(string(utf8Data))
Output:

true
hello

func MapToSlice added in v2.1.2

func MapToSlice[T any, K comparable, V any](aMap map[K]V, iteratee func(K, V) T) []T

MapToSlice convert map to slice based on iteratee function. Play: https://go.dev/play/p/dmX4Ix5V6Wl

Example
aMap := map[string]int{"a": 1, "b": 2, "c": 3}
result := MapToSlice(aMap, func(key string, value int) string {
	return key + ":" + strconv.Itoa(value)
})

fmt.Println(result) //[]string{"a:1", "c:3", "b:2"} (random order)
Output:

func StructToMap

func StructToMap(value any) (map[string]any, error)

StructToMap convert struct to map, only convert exported struct field map key is specified same as struct field tag `json` value. Play: https://go.dev/play/p/KYGYJqNUBOI

Example
type People struct {
	Name string `json:"name"`
	age  int
}
p := People{
	"test",
	100,
}
pm, _ := StructToMap(p)

fmt.Println(pm)
Output:

map[name:test]

func ToBool

func ToBool(s string) (bool, error)

ToBool convert string to boolean. Play: https://go.dev/play/p/ARht2WnGdIN

Example
cases := []string{"1", "true", "True", "false", "False", "0", "123", "0.0", "abc"}

for i := 0; i < len(cases); i++ {
	result, _ := ToBool(cases[i])
	fmt.Println(result)
}
Output:

true
true
true
false
false
false
false
false
false

func ToBytes

func ToBytes(value any) ([]byte, error)

ToBytes convert value to byte slice. Play: https://go.dev/play/p/fAMXYFDvOvr

Example
result1, _ := ToBytes(1)
result2, _ := ToBytes("abc")
result3, _ := ToBytes(true)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

[0 0 0 0 0 0 0 1]
[97 98 99]
[116 114 117 101]

func ToChannel added in v2.1.2

func ToChannel[T any](array []T) <-chan T

ToChannel convert a slice of elements to a read-only channel. Play: https://go.dev/play/p/hOx_oYZbAnL

Example
ch := ToChannel([]int{1, 2, 3})
result1 := <-ch
result2 := <-ch
result3 := <-ch

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

1
2
3

func ToChar

func ToChar(s string) []string

ToChar convert string to char slice. Play: https://go.dev/play/p/JJ1SvbFkVdM

Example
result1 := ToChar("")
result2 := ToChar("abc")
result3 := ToChar("1 2#3")

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

[]
[a b c]
[1   2 # 3]

func ToFloat

func ToFloat(value any) (float64, error)

ToFloat convert value to float64, if input is not a float return 0.0 and error. Play: https://go.dev/play/p/4YTmPCibqHJ

Example
result1, _ := ToFloat("")
result2, _ := ToFloat("abc")
result3, _ := ToFloat("-1")
result4, _ := ToFloat("-.11")
result5, _ := ToFloat("1.23e3")
result6, _ := ToFloat(true)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
Output:

0
0
-1
-0.11
1230
0

func ToInt

func ToInt(value any) (int64, error)

ToInt convert value to int64 value, if input is not numerical, return 0 and error. Play: https://go.dev/play/p/9_h9vIt-QZ_b

Example
result1, _ := ToInt("123")
result2, _ := ToInt("-123")
result3, _ := ToInt(float64(12.3))
result4, _ := ToInt("abc")
result5, _ := ToInt(true)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
Output:

123
-123
12
0
0

func ToInterface added in v2.2.0

func ToInterface(v reflect.Value) (value interface{}, ok bool)

ToInterface converts reflect value to its interface type. Play: https://go.dev/play/p/syqw0-WG7Xd

Example
val := reflect.ValueOf("abc")
iVal, ok := ToInterface(val)

fmt.Printf("%T\n", iVal)
fmt.Printf("%v\n", iVal)
fmt.Println(ok)
Output:

string
abc
true

func ToJson

func ToJson(value any) (string, error)

ToJson convert value to a json string. Play: https://go.dev/play/p/2rLIkMmXWvR

Example
aMap := map[string]int{"a": 1, "b": 2, "c": 3}
result1, err := ToJson(aMap)
if err != nil {
	fmt.Printf("%v", err)
}
fmt.Println(result1)
Output:

{"a":1,"b":2,"c":3}

func ToMap added in v2.1.2

func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V

ToMap convert a slice of structs to a map based on iteratee function. Play: https://go.dev/play/p/tVFy7E-t24l

Example
type Message struct {
	name string
	code int
}
messages := []Message{
	{name: "Hello", code: 100},
	{name: "Hi", code: 101},
}
result := ToMap(messages, func(msg Message) (int, string) {
	return msg.code, msg.name
})

fmt.Println(result)
Output:

map[100:Hello 101:Hi]

func ToPointer added in v2.1.1

func ToPointer[T any](value T) *T

ToPointer returns a pointer to passed value. Play: https://go.dev/play/p/ASf_etHNlw1

Example
result := ToPointer(123)
fmt.Println(*result)
Output:

123

func ToRawStdBase64 added in v2.3.0

func ToRawStdBase64(value any) string

ToRawStdBase64 convert data to raw standard base64 encoding. Play: https://go.dev/play/p/wSAr3sfkDcv

Example
// if you want to see the result, please use 'base64.RawStdEncoding.DecodeString()' to decode the result
stringVal := "hello"
afterEncode := ToRawStdBase64(stringVal)
fmt.Println(afterEncode)

byteSliceVal := []byte("hello")
afterEncode = ToRawStdBase64(byteSliceVal)
fmt.Println(afterEncode)

intVal := 123
afterEncode = ToRawStdBase64(intVal)
fmt.Println(afterEncode)

mapVal := map[string]any{"a": "hi", "b": 2, "c": struct {
	A string
	B int
}{"hello", 3}}
afterEncode = ToRawStdBase64(mapVal)
fmt.Println(afterEncode)

floatVal := 123.456
afterEncode = ToRawStdBase64(floatVal)
fmt.Println(afterEncode)

boolVal := true
afterEncode = ToRawStdBase64(boolVal)
fmt.Println(afterEncode)

errVal := errors.New("err")
afterEncode = ToRawStdBase64(errVal)
fmt.Println(afterEncode)
Output:

aGVsbG8
aGVsbG8
MTIz
eyJhIjoiaGkiLCJiIjoyLCJjIjp7IkEiOiJoZWxsbyIsIkIiOjN9fQ
MTIzLjQ1Ng
dHJ1ZQ
ZXJy

func ToRawUrlBase64 added in v2.3.0

func ToRawUrlBase64(value any) string

ToRawUrlBase64 convert data to raw URL base64 encoding. Play: https://go.dev/play/p/HwdDPFcza1O

Example
// if you want to see the result, please use 'base64.RawURLEncoding.DecodeString()' to decode the result

stringVal := "hello"
afterEncode := ToRawUrlBase64(stringVal)
fmt.Println(afterEncode)

byteSliceVal := []byte("hello")
afterEncode = ToRawUrlBase64(byteSliceVal)
fmt.Println(afterEncode)

intVal := 123
afterEncode = ToRawUrlBase64(intVal)
fmt.Println(afterEncode)

mapVal := map[string]any{"a": "hi", "b": 2, "c": struct {
	A string
	B int
}{"hello", 3}}
afterEncode = ToRawUrlBase64(mapVal)
fmt.Println(afterEncode)

floatVal := 123.456
afterEncode = ToRawUrlBase64(floatVal)
fmt.Println(afterEncode)

boolVal := true
afterEncode = ToRawUrlBase64(boolVal)
fmt.Println(afterEncode)

errVal := errors.New("err")
afterEncode = ToRawUrlBase64(errVal)
fmt.Println(afterEncode)
Output:

aGVsbG8
aGVsbG8
MTIz
eyJhIjoiaGkiLCJiIjoyLCJjIjp7IkEiOiJoZWxsbyIsIkIiOjN9fQ
MTIzLjQ1Ng
dHJ1ZQ
ZXJy

func ToStdBase64 added in v2.3.0

func ToStdBase64(value any) string

ToStdBase64 convert data to standard base64 encoding. Play: https://go.dev/play/p/_fLJqJD3NMo

Example
// if you want to see the result, please use 'base64.StdEncoding.DecodeString()' to decode the result

afterEncode := ToStdBase64(nil)
fmt.Println(afterEncode)

stringVal := "hello"
afterEncode = ToStdBase64(stringVal)
fmt.Println(afterEncode)

byteSliceVal := []byte("hello")
afterEncode = ToStdBase64(byteSliceVal)
fmt.Println(afterEncode)

intVal := 123
afterEncode = ToStdBase64(intVal)
fmt.Println(afterEncode)

mapVal := map[string]any{"a": "hi", "b": 2, "c": struct {
	A string
	B int
}{"hello", 3}}
afterEncode = ToStdBase64(mapVal)
fmt.Println(afterEncode)

floatVal := 123.456
afterEncode = ToStdBase64(floatVal)
fmt.Println(afterEncode)

boolVal := true
afterEncode = ToStdBase64(boolVal)
fmt.Println(afterEncode)

errVal := errors.New("err")
afterEncode = ToStdBase64(errVal)
fmt.Println(afterEncode)
Output:


aGVsbG8=
aGVsbG8=
MTIz
eyJhIjoiaGkiLCJiIjoyLCJjIjp7IkEiOiJoZWxsbyIsIkIiOjN9fQ==
MTIzLjQ1Ng==
dHJ1ZQ==
ZXJy

func ToString

func ToString(value any) string

ToString convert value to string for number, string, []byte, will convert to string for other type (slice, map, array, struct) will call json.Marshal. Play: https://go.dev/play/p/nF1zOOslpQq

Example
result1 := ToString("")
result2 := ToString(nil)
result3 := ToString(0)
result4 := ToString(1.23)
result5 := ToString(true)
result6 := ToString(false)
result7 := ToString([]int{1, 2, 3})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
fmt.Println(result7)
Output:


0
1.23
true
false
[1,2,3]

func ToUrlBase64 added in v2.3.0

func ToUrlBase64(value any) string

ToUrlBase64 convert data to URL base64 encoding. Play: https://go.dev/play/p/C_d0GlvEeUR

Example
// if you want to see the result, please use 'base64.URLEncoding.DecodeString()' to decode the result

stringVal := "hello"
afterEncode := ToUrlBase64(stringVal)
fmt.Println(afterEncode)

byteSliceVal := []byte("hello")
afterEncode = ToUrlBase64(byteSliceVal)
fmt.Println(afterEncode)

intVal := 123
afterEncode = ToUrlBase64(intVal)
fmt.Println(afterEncode)

mapVal := map[string]any{"a": "hi", "b": 2, "c": struct {
	A string
	B int
}{"hello", 3}}
afterEncode = ToUrlBase64(mapVal)
fmt.Println(afterEncode)

floatVal := 123.456
afterEncode = ToUrlBase64(floatVal)
fmt.Println(afterEncode)

boolVal := true
afterEncode = ToUrlBase64(boolVal)
fmt.Println(afterEncode)

errVal := errors.New("err")
afterEncode = ToUrlBase64(errVal)
fmt.Println(afterEncode)
Output:

aGVsbG8=
aGVsbG8=
MTIz
eyJhIjoiaGkiLCJiIjoyLCJjIjp7IkEiOiJoZWxsbyIsIkIiOjN9fQ==
MTIzLjQ1Ng==
dHJ1ZQ==
ZXJy

func Utf8ToGbk added in v2.2.2

func Utf8ToGbk(bs []byte) ([]byte, error)

Utf8ToGbk convert utf8 encoding data to GBK encoding data. Play: https://go.dev/play/p/9FlIaFLArIL

Example
utf8Data := []byte("hello")
gbkData, _ := Utf8ToGbk(utf8Data)

fmt.Println(utf8.Valid(utf8Data))
fmt.Println(validator.IsGBK(gbkData))
Output:

true
true

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL