Go 常用函数
获取当前时间戳
package main
import (
"fmt"
"time"
)
func main(){
timeUnix:=time.Now().Unix()
fmt.Println(timeUnix) // 1598794757
}
获取年月日时分秒
package main
import (
"fmt"
"time"
)
func main(){
year:=time.Now().Year() //年
month:=time.Now().Month() //月
day:=time.Now().Day() //日
hour:=time.Now().Hour() //时
minute:=time.Now().Minute() //分钟
second:=time.Now().Second() //秒
fmt.Println(year, month, day, hour, minute, second) // 2020 August 30 21 49 10
}
当前时间格式化
package main
import (
"fmt"
"time"
)
func main(){
timeStr:=time.Now().Format("2006-01-02 15:04:05") // 2006-01-02 15:04:05据说是golang的诞生时间,固定写法
fmt.Println(timeStr) // 2020-08-30 21:40:30
}
时间戳格式化
package main
import (
"fmt"
"time"
)
func main(){
timeUnix:=time.Now().Unix()
formatTimeStr:=time.Unix(timeUnix,0).Format("2006-01-02 15:04:05")
fmt.Println(formatTimeStr) // 2020-08-30 21:42:13
}
格式化时间转时间戳
package main
import (
"fmt"
"time"
)
func main(){
formatTime, err := time.ParseInLocation("2006-01-02 15:04:05", "2020-02-02 20:20:20", time.Local)
if err == nil{
timeUnix := formatTime.Unix()
fmt.Println(timeUnix) // 1580674820
}
}
json 序列化
结构体序列化
package main
import (
"encoding/json"
"fmt"
)
type Person struct{
Name string `json:"name"`
Age int `json:"age"`
Gender string `json:gender`
}
func main(){
person := Person{
Name: "Tom",
Age: 18,
Gender: "男",
}
data, err := json.Marshal(person)
if err == nil{
fmt.Println(string(data)) // {"name":"Tom","age":18,"Gender":"男"}
}
}
切片序列化
package main
import (
"encoding/json"
"fmt"
)
func main(){
var person []map[string]interface{}
p1 := make(map[string]interface{})
p1["name"] = "Tom"
p1["age"] = 18
p1["gender"] = "男"
person = append(person, p1)
data, err := json.Marshal(person)
if err == nil{
fmt.Println(string(data)) // [{"age":18,"gender":"男","name":"Tom"}]
}
}
json 反序列化
package main
import (
"encoding/json"
"fmt"
)
func main(){
str := "{\"name\":\"Tom\",\"age\":18,\"gender\":\"男\"}"
var person map[string]interface{}
err := json.Unmarshal([]byte(str), &person)
if err == nil {
fmt.Println(person) // map[age:18 gender:男 name:Tom]
}
}
切片随机取出元素
package main
import (
"fmt"
"time"
"math/rand"
)
func main(){
unPatientIdList := []int{1, 2, 3, 4}
rand.Seed(time.Now().Unix())
randomNum := rand.Intn(len(unPatientIdList)) // 取出的范围0-3
fmt.Println(unPatientIdList[randomNum])
}
获取中文字符串长度
import "unicode/utf8"
func main(){
fmt.Println(utf8.RuneCountInString("PHP 是世界上最好的语言!")) //14
}
Md5加密
import (
"crypto/md5"
"encoding/hex"
)
func main(){
str := 123
h := md5.New()
h.Write([]byte(str)
cipherStr := h.Sum(nil)
fmt.Println(hex.EncodeToString(cipherStr))
}
稳定排序
type Word struct {
str string
length int
}
type Words []Word
func main() {
var words Words
sort.SliceStable(words, func(p, q int) bool {
return words[p].length < words[q].length
})
}
整型和浮点型操作
向下取整
math.Floot()
向上取整
math.Ceil()
保留两位小数
fmt.Sprintf("%.2f", 3.1415926)
两数相除,保留两位小数
a := 3
b := 7
num, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", float64(a)/float64(b)), 64) // 保留2位小数
int/int64 转字符串
s := strconv.Itoa(97) // s == "97"
使用 strconv.FormatInt 以给定的进制数(十进制、十六进制)格式化 int64。
var n int64 = 97
s := strconv.FormatInt(n, 10) // s == "97" (十进制)
s := strconv.FormatInt(n, 16) // s == "61" (十六进制)
字符串转 int/int64
使用 strconv.Atoi 将十进制字符串解析为 int 。
s := "97"
if n, err := strconv.Atoi(s); err == nil {
fmt.Println(n+1)
} else {
fmt.Println(s, "is not an integer.")
}
// Output: 98
float64 转 int
func f2i(f float64) int {
i, _ := strconv.Atoi(fmt.Sprintf("%1.0f", f))
return i
}
使用 strconv.ParseInt 解析一个十进制字符串(以10为基数),并检查其是否适合 int64。
s := "97"
n, err := strconv.ParseInt(s, 10, 64)
if err == nil {
fmt.Printf("%d of type %T", n, n)
}
// Output: 97 of type int64
urlencode
import (
"fmt"
"net/url"
)
func main() {
// url encode
v := url.Values{}
v.Add("url", "https://codelife.xin")
body := v.Encode()
fmt.Println(v)
fmt.Println(body)
// url decode
m, _ := url.ParseQuery(body)
fmt.Println(m)
}