Go 常用知识点及实例

2020/01/12 Go 知识点

时间

https://www.cnblogs.com/followyou/p/12187949.html

error

https://www.cnblogs.com/followyou/p/12185514.html

断言

https://www.cnblogs.com/followyou/p/12185509.html

定义函数类型

type ExposureQualityService interface {

}

type NewExposureQualityServiceFunc func() ExposureQualityService

格式转换

https://www.cnblogs.com/followyou/p/12194128.html

打断点

fmt.Println(exposureData)
os.Exit(1)

休眠

func Sleep(d Duration)

  const (
  Nanosecond Duration = 1
  Microsecond = 1000 * Nanosecond
  Millisecond = 1000 * Microsecond
  Second = 1000 * Millisecond
  Minute = 60 * Second
  Hour = 60 * Minute
  )

urlencode

  • 字符串 ```go package main

import ( “fmt” “net/url” )

func main() { query := “Hellö Wörld@Golang” fmt.Println(url.QueryEscape(query)) }

- 多个参数
```go
package main

import (
	"fmt"
	"net/url"
)

func main() {
	params := url.Values{}
	params.Add("name", "@Rajeev")
	params.Add("phone", "+919999999999")

	fmt.Println(params.Encode())
}
  • 编码路径 ```go package main

import ( “fmt” “net/url” )

func main() { path := “path with?reserved+characters” fmt.Println(url.PathEscape(path)) }

// Output // path%20with%3Freserved+characters


解码参考 [https://www.urldecoder.io/golang/](https://www.urldecoder.io/golang/)


# 去除首尾空格
```go
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := " hello world!  "
	str = strings.TrimSpace(str)
	fmt.Println(str)
}

字符串截取

str := "oeryoqpqpqepqw"
content = str[1:10]
fmt.println(content)

ip转number

func Ip2long(ip string) int64 {
	var cip net.IP
	cip = []byte(ip)
	// ipv4
	if cip.To4() != nil {
		num, _ := exnet.IP2Long(cip)
		return int64(num)
	} else {
		bigint := ipv6ToInt(ip)
		return bigint
	}
}

func ipv6ToInt(ip string) int64 {
	IPv6Int := big.NewInt(0)
	IPv6Int.SetBytes(net.ParseIP(ip).To4())
	return IPv6Int.Int64()
}

go test

显示单元测试详细信息且指定测试方法

 go test -v data-structure/heap/btree_heap.go data-structure/heap/btree_heap_test.go -test.run TestHeap_Replace

Go 随机数

// 随机数种子,确保每次初始化真随机;
// uses the provided seed value to initialize the generator to a deterministic state.
s := rand.NewSource(time.Now().UnixNano())
token := rand.New(s).Intn(1000000)

// or
rand.Seed(time.Now().UnixNano())
token := rand.New(s).Intn(1000000)

Refer:

chan

https://www.cnblogs.com/followyou/p/13799845.html

file

获取文件MIME

net/http 包下的方法 http.DetectContentType() 会读取内容的前 512 个字节的内容,并根据它们判断文件的类型,然后返回该文件的 MIME 类型。如果是未知类型,则会返回 application/octet-stream


import (
    "os"
    "fmt"
    "net/http"
)

func main() {

    // Open File
    f, err := os.Open("test.pdf")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    // Get the content
    contentType, err := GetFileContentType(f)
    if err != nil {
        panic(err)
    }

    fmt.Println("Content Type: " + contentType)
}

func GetFileContentType(out *os.File) (string, error) {

    // 只需要前 512 个字节就可以了
    buffer := make([]byte, 512)

    _, err := out.Read(buffer)
    if err != nil {
        return "", err
    }

    contentType := http.DetectContentType(buffer)

    return contentType, nil
}

Search

    Table of Contents