Golang 笔记(个人记录,欢迎吐槽)

Golang 字符串去空格 去空,去重, 转数组数组

func RemoveDuplicatesAndEmpty(Str string) []string {
	slc := strings.Split(strings.Replace(Str, " ", "", -1), ",")
	var result []string
	tempMap := map[string]byte{}
	for _, e := range slc {
		lastLen := len(tempMap)
		tempMap[e] = 0
		if len(tempMap) != lastLen && e != "" {
			result = append(result, e)
		}
	}
	return result
}

Golang 随机生成n位数的字符串

import (
	"math/rand"
	"strings"
	"time"
)
const (
	KC_RAND_KIND_NUM   = 0  // 纯数字
	KC_RAND_KIND_LOWER = 1  // 小写字母
	KC_RAND_KIND_UPPER = 2  // 大写字母
	KC_RAND_KIND_ALL   = 3  // 数字、大小写字母
)
// 随机字符串
func RandString(size int, kind int) string {
	iKind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
	isAll := kind > 2 || kind < 0
	rand.Seed(time.Now().UnixNano())
	for i :=0; i < size; i++ {
		if isAll {
			iKind = rand.Intn(3)
		}
		scope, base := kinds[iKind][0], kinds[iKind][1]
		result[i] = uint8(base+rand.Intn(scope))
	}
	return string(result)
}

Golang 判断字符串是否是纯字母

func StrAllLetter(str string) bool {
	str = strings.Replace(str, " ", "", -1)
	match, _ := regexp.MatchString(`^[A-Za-z]+$`, str)
	return match
}

Golang 数据表格导出

func ExcelExport(ctx *gin.Context, header []string, data []map[string]interface{}, sheetName string) {
	timeStr:=time.Now().Format("2006-01-02 15:04:05")
	var file *xlsx.File
	var sheet *xlsx.Sheet
	var row *xlsx.Row
	var cell *xlsx.Cell

	style := &xlsx.Style{}
	style.Fill = *xlsx.NewFill("solid", "EFEFDE", "EFEFDE")
	style.Border = xlsx.Border{RightColor: "FF"}
	file = xlsx.NewFile()
	sheet, _ = file.AddSheet(sheetName)
	row = sheet.AddRow()
	for i := 0; i < len(header); i++ {
		cell = row.AddCell()
		cell.Value = header[i]
		cell.SetStyle(style)
	}
	for _, obj := range data {
		row = sheet.AddRow()
		for i := 0;i <len(header);i++{
			cell = row.AddCell()
			cell.Value = types.InterfaceToString(obj[header[i]])
		}
	}
	url := timeStr+".xlsx"
	file.Save(url)
	ctx.Writer.Header().Set("Content-Type", "application/octet-stream")
	disposition := fmt.Sprintf("attachment; filename=\"%s-%s.xlsx\"", "robot", time.Now().Format("2006-01-02 15:04:05"))
	ctx.Writer.Header().Set("Content-Disposition", disposition)
	_ = file.Write(ctx.Writer)
	return
}

Golang 数据interface类型转字符串

import (
	"encoding/json"
	"strconv"
)

func InterfaceToString(value interface{}) string {
	// interface 转 string
	var key string
	if value == nil {
		return key
	}

	switch value.(type) {
	case float64:
		ft := value.(float64)
		key = strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		key = strconv.Itoa(it)
	case uint:
		it := value.(uint)
		key = strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		key = strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		key = strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		key = strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		key = strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		key = strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		key = strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		key = strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		key = strconv.FormatUint(it, 10)
	case string:
		key = value.(string)
	case []byte:
		key = string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		key = string(newValue)
	}

	return key
}

Golang 数据MD5

import (
	"crypto/md5"
	"encoding/hex"
)

func GenMd5(toAuth []byte) string {
	md5Ctx := md5.New()
	md5Ctx.Write(toAuth)
	cipherStr := md5Ctx.Sum(nil)
	md5Str := hex.EncodeToString(cipherStr)
	return md5Str
}

Golang 适合有struct的Http请求

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

func RequestHttpClient(dest interface{}, method, url string, param, body url.Values) (err error) {
	URL := url + "?" + param.Encode()
	client := http.Client{
		Timeout: 2 * time.Second,
	}
	var reader io.Reader
	if body != nil {
		reader = strings.NewReader(body.Encode())
	}
	request, err := http.NewRequest(method, URL, reader)
	if err != nil {
		return
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	response, err := client.Do(request)
	if err != nil {
		return
	}
	defer response.Body.Close()
	respBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}
	err = json.Unmarshal(respBody, dest)
	if err != nil {
		return
	}
	return
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值