1024程式設計師節 | 全民狂歡,拒絕加班2020-10-24,golang實用工具方法分享,拒絕加班~

超級戰鬥王發表於2020-10-24

重要的事情說三遍,拒絕加班!拒絕加班!拒絕加班!

分享一些日常積累的實用golang工具小方法,從此拒絕加班~

結構體轉json字串

func DumpString(v interface{}) (str string) {
	bs, err := json.Marshal(v)
	b := bytes.Buffer{}
	if err != nil {
		b.WriteString("{err:\"json format error.")
		b.WriteString(err.Error())
		b.WriteString("\"}")
	} else {
		b.Write(bs)
	}
	str = b.String()
	return str
}

獲取指定長度指定字首的uuid 

import (
	"crypto/rand"
	"fmt"
	"math/big"
	mathrandom "math/rand"
	"time"
)

func GenerateUUID(prefex string, uuidLen int) string {
	var character = []byte("abcdefgijklmnopqrstuvwxyz0123456789")
	var chLen = len(character)
	buf := make([]byte, uuidLen, uuidLen)
	max := big.NewInt(int64(chLen))
	for i := 0; i < uuidLen; i++ {
		random, err := rand.Int(rand.Reader, max)
		if err != nil {
			mathrandom.Seed(time.Now().UnixNano())
			buf[i] = character[mathrandom.Intn(chLen)]
			continue
		}
		buf[i] = character[random.Int64()]
	}
	return fmt.Sprintf("%s-%s", prefex, string(buf))
}

深克隆結構體

func Clone(i interface{}) interface{} {
	typ := reflect.TypeOf(i)
	for typ.Kind() == reflect.Ptr {
		typ = typ.Elem()
	}
	vl := reflect.ValueOf(i)
	if vl.IsNil() {
		return reflect.New(typ)
	}
	for vl.Kind() == reflect.Ptr {
		vl = vl.Elem()
	}
	el := reflect.New(typ).Elem()
	el.Set(vl)
	return el.Addr().Interface()
}

淺拷貝結構體

func Copy(dst interface{}, src interface{}) error {
	if dst == nil {
		return fmt.Errorf("dst cannot be nil")
	}
	if src == nil {
		return fmt.Errorf("src cannot be nil")
	}
	bytes, err := json.Marshal(src)
	if err != nil {
		return fmt.Errorf("Unable to marshal src: %s", err)
	}
	err = json.Unmarshal(bytes, dst)
	if err != nil {
		return fmt.Errorf("Unable to unmarshal into dst: %s", err)
	}
	return nil
}

url是否合法

func IsValidHttpUrl(urlPath string) bool {
	u := urlPath

	var httpPre = regexp.MustCompile(`^https?://`)
	
	// 協議校驗
	if !httpPre.Match([]byte(u)) {
		return false
	}

	// url format校驗
	r, err := url.Parse(urlPath)
	if err != nil {
		return false
	}

	//必須為可解析的ip或域名
	if net.ParseIP(r.Hostname()) == nil {
		ips, err := net.LookupIP(r.Hostname())
		if err != nil || len(ips) == 0 {
			return false
		}
	}

	return true
}

是否為ipv6

func IsIPV6(target string) bool {
	ip := net.ParseIP(target)
	if ip != nil {
		if ip.To4() == nil && ip.To16() != nil {
			return true
		}
	}
	return false
}

是否為ipv4

func ValidIP4(ipAddress string) bool {
	ipAddress = strings.Trim(ipAddress, " ")

	re, _ := regexp.Compile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`)
	if re.MatchString(ipAddress) {
		return true
	}
	return false
}

base64編碼

func Base64Encode(s string) string {

	return base64.StdEncoding.EncodeToString([]byte(s))
}

base64解碼

func Base64Decode(s string) (string, error) {
	r, err := base64.StdEncoding.DecodeString(s)
	if err != nil {
		return "", err
	}
	return string(r), nil
}

md5加密

func MD5Strings(strings ...string) string {
	h := md5.New()
	for _, s := range strings {
		io.WriteString(h, s)
	}
	return fmt.Sprintf("%x", h.Sum(nil))
}

陣列轉換為map

func ConvertSliceToMap(s []string) map[string]struct{} {
	ret := map[string]struct{}{}
	for _, v := range s {
		ret[v] = struct{}{}
	}
	return ret
}

為了減少加班,持續分享中...

相關文章