1. strings —字符串函数:
    1. 包含:
      fmt.Println(strings.Contains("abc","a"))  // 输出 true
    2. 分割:
      fmt.Println(strings.Split("a,b,c",","))  // 输出 [a b c]
    3. 拼接:
      fmt.Println(strings.Join([]string{"a","b","c"},","))  // 输出 a,b,c
    4. 去除首尾指定字符:
      fmt.Println(strings.Trim("-!abc#","-#!"))  // 输出 abc
    5. 替换:
      fmt.Println(strings.Replace("abc","b","-",1))  // 输出 a-c
    6. 重复字符串:
      fmt.Println(strings.Repeat("a",3))  // 输出 aaa
    7. 检索位置:
      fmt.Println(strings.Index("abc","b"))  // 输出 1
    8. 去除空格:
      fmt.Println(strings.Fields(" a b c "))  // 输出 [a b c]
      fmt.Println(strings.TrimSpace(" a b c "))  // 输出 a b c(前后无空格)
  2. strconv —字符串转换:
    1. Append —将其它类型添加到 byte 切片中:
      1. 整型:
        fmt.Println(string(strconv.AppendInt([]byte("abc"),1000,10)))  // 输出 abc1000
      2. 布尔:
        fmt.Println(string(strconv.AppendBool([]byte("abc"),false)))  // 输出 abcfalse
      3. 字符串:
        fmt.Println(string(strconv.AppendQuote([]byte("abc"),"你好吗")))  // 输出 abc"你好吗"
    2. Format —其它类型转字符串:
      1. 整型:
        fmt.Println(strconv.Itoa(1000))  // 输出 1000
      2. 浮点型:
        fmt.Println(strconv.FormatFloat(3.1415926, 'g', 3, 64))  // 输出 3.14
      3. 布尔:
        fmt.Println(strconv.FormatBool(false))  // 输出 false
    3. Parse —字符串转为其它类型:
      1. 整型:
        fmt.Println(strconv.Atoi("1000"))  // 输出 1000 <nil>
      2. 浮点型:
        fmt.Println(strconv.ParseFloat("3.1415926",64))  // 输出 3.1415926 <nil>
      3. 布尔:
        fmt.Println(strconv.ParseBool("false"))  // 输出 false <nil>
    4. Quote —特殊字符转义:
      fmt.Println(strconv.Quote(`abc\r\s\t`))  // 输出 "abc\\r\\s\\t"
    5. 其它:
      1. string 转 []byte:
        str := "abc"
        fmt.Println([]byte(str))
      2. []byte 转 string:
        by := []byte{97,98,99}
        fmt.Println(string(by))
  3. encoding —编解码
    1. encoding/json —生成/解析 json:
      1. 生成:
        package main
        import (
        "encoding/json"
        "fmt"
        )
        type Student struct {
        Name string `json:"name"`
        }
        type PeopleList struct {
        People []Student `json:"people"`
        }
        func main()  {
        data := PeopleList{
        []Student{
        {Name:"xiaoming"},
        {Name:"xiaomei"},
        }}
        res,_ := json.Marshal(data)
        fmt.Println(string(res))
        }
        // 输出 {"people":[{"name":"xiaoming"},{"name":"xiaomei"}]}
      2. 解析:
        package main
        import (
        "encoding/json"
        "fmt"
        )
        type Student struct {
        Name string `json:"name"`
        }
        type PeopleList struct {
        People []Student `json:"people"`
        }
        func main()  {
        str := `{"people":[{"name":"xiaoming"},{"name":"xiaomei"}]}`
        var res PeopleList
        json.Unmarshal([]byte(str), &res)
        fmt.Println(res)
        }
        // 输出 {[{xiaoming} {xiaomei}]}
    2. encoding/xml —生成/解析 xml:
      1. 生成:
        package main
        import (
        "encoding/xml"
        "fmt"
        )
        type People struct {
        XMLName xml.Name `xml:"people"`
        Version string   `xml:"version,attr"`
        Svs     []Student `xml:"student"`
        }
        type Student struct {
        Name string `xml:"name"`
        }
        func main() {
        v := &People{Version: "1"}
        v.Svs = append(v.Svs, Student{Name:"xiaoming"})
        v.Svs = append(v.Svs, Student{Name:"xiaomei"})
        output,_ := xml.Marshal(v)
        fmt.Println(string([]byte(xml.Header)))
        fmt.Println(string(output))
        }
        // 输出
        <?xml version="1.0" encoding="UTF-8"?>
        <people version="1"><student><name>xiaoming</name></student><student><name>xiaomei</name></student></people>
      2. 解析:
        package main
        import (
        "encoding/xml"
        "fmt"
        )
        type People struct {
        XMLName     xml.Name `xml:"people"`
        Version     string   `xml:"version,attr"`
        Svs         []Student `xml:"student"`
        }
        type Student struct {
        Name string   `xml:"name"`
        }
        func main() {
        data := []byte(`
        <?xml version="1.0" encoding="utf-8"?>
        <people version="1">
        <student>
        <name>xiaoming</name>
        </student>
        <student>
        <name>xiaomei</name>
        </student>
        </people>
        `)
        v := People{}
        err := xml.Unmarshal(data, &v)
        if err != nil {
        fmt.Printf("error: %v", err)
        return
        }
        fmt.Println(v)
        }
        // 输出
        {{ people} 1 [{xiaoming} {xiaomei}]}
    3. encoding/hex —十六进制编/解码:
      package main
      import (
      "encoding/hex"
      "fmt"
      )
      func main() {
      str := []byte("hello")
      // 编码
      encode_str := hex.EncodeToString(str)
      fmt.Println(encode_str)  // 输出 68656c6c6f
      // 解码
      decode_byte, _ := hex.DecodeString(encode_str)
      fmt.Println(string(decode_byte))  // 输出 hello
      }
    4. encoding/base64 —BASE64加/解密:
      package main
      import (
      "encoding/base64"
      "fmt"
      )
      func base64Encode(str []byte) []byte {
      return []byte(base64.StdEncoding.EncodeToString(str))
      }
      func base64Decode(str []byte) ([]byte, error){
      return base64.StdEncoding.DecodeString(string(str))
      }
      func main(){
      str := "hello"
      enc_str := base64Encode([]byte(str))
      fmt.Println(string(enc_str))  // 输出 aGVsbG8=
      dec_str,_ := base64Decode(enc_str)
      fmt.Println(string(dec_str))  // 输出 hello
      }
  4. regexp —正则处理:
    1. 验证:
      fmt.Println(regexp.MatchString("[a-z]*","abc"))  // 输出 true <nil>
    2. 获取:
      r, _ := regexp.Compile("[0-9]")
      match := r.Find([]byte("a1c"))
      fmt.Println(string(match))  // 输出 1
    3. 替换:
      r, _ := regexp.Compile("[0-9]")
      match := r.ReplaceAll([]byte("a1c"),[]byte(""))
      fmt.Println(string(match))  // 输出 ac
  5. crypto —加密/解密:
    1. crypto/md5 —MD5加密:
      package main
      import (
      "crypto/md5"
      "encoding/hex"
      "io"
      "fmt"
      )
      func main(){
      h := md5.New()
      io.WriteString(h, "123456")
      cipherStr := h.Sum(nil)
      fmt.Println(hex.EncodeToString(cipherStr))  // 输出 e10adc3949ba59abbe56e057f20f883e
      }
    2. crypto/sha1 —SHA1加密:
      package main
      import (
      "crypto/sha1"
      "encoding/hex"
      "io"
      "fmt"
      )
      func main(){
      h := sha1.New()
      io.WriteString(h, "123456")
      cipherStr := h.Sum(nil)
      fmt.Println(hex.EncodeToString(cipherStr))  // 输出 7c4a8d09ca3762af61e59520943dc26494f8941b
      }
    3. crypto/sha256 —SHA256加密:
      package main
      import (
      "crypto/sha256"
      "encoding/hex"
      "io"
      "fmt"
      )
      func main(){
      h := sha256.New()
      io.WriteString(h, "123456")
      cipherStr := h.Sum(nil)
      fmt.Println(hex.EncodeToString(cipherStr))  // 输出 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
      }
  6. time —时间处理:
    1. 获取时间缀:
      fmt.Println(time.Now().Unix())  // 输出 1589153929
    2. 解析/格式化:
      package main
      import (
      "fmt"
      "time"
      )
      func main(){
      t,_ := time.ParseInLocation("2006/01月02日 15:04:05", "2019/08月11日 11:50:35", time.Local)
      fmt.Println(t.String())  // 输出 2019-08-11 11:50:35 +0800 PST
      fmt.Println(t.Year())  // 输出 2019
      fmt.Println(t.Format("2006年01月02日"))  // 输出 2019年08月11日(时间字符串)
      fmt.Println(t.Unix())  // 输出 1565495435(时间缀)
      }
    3. 生成:
      package main
      import (
      "fmt"
      "time"
      )
      func main() {
      t := time.Date(2019, 8, 11, 12, 11, 12, 0, time.Local)
      fmt.Println(t.String())  // 输出 2019-08-11 12:11:12 +0800 PST
      fmt.Println(t.Format("2006-01-02"))  // 输出 2019-08-11
      fmt.Println(t.Unix())  // 输出 1565496672
      }
    4. 获取整点时间:
      package main
      import (
      "fmt"
      "time"
      )
      func main() {
      t := time.Now()
      fmt.Println(t.String())  // 输出 2020-05-11 07:55:22.083553 +0800 PST m=+0.000083752
      fmt.Println(t.Truncate(time.Hour))  // 输出 2020-05-11 07:00:00 +0800 PST
      fmt.Println(t.Round(time.Hour))  // 输出 2020-05-11 08:00:00 +0800 PST
      }
    5. 时间加减:
      1. 相加(获取相加后的时间):
        package main
        import (
        "fmt"
        "time"
        )
        func main() {
        // Add 时间相加
        now := time.Now()
        // 1分钟前
        m, _ := time.ParseDuration("-1m")
        m1 := now.Add(m)
        fmt.Println(m1)
        // 1个小时前
        h, _ := time.ParseDuration("-1h")
        h1 := now.Add(h)
        fmt.Println(h1)
        // 1天前
        d, _ := time.ParseDuration("-24h")
        d1 := now.Add(d)
        fmt.Println(d1)
        // 1分钟后
        mm, _ := time.ParseDuration("1m")
        mm1 := now.Add(mm)
        fmt.Println(mm1)
        // 1小时后
        hh, _ := time.ParseDuration("1h")
        hh1 := now.Add(hh)
        fmt.Println(hh1)
        // 1天后
        dd, _ := time.ParseDuration("24h")
        dd1 := now.Add(dd)
        fmt.Println(dd1)
        }
        // 输出
        2020-07-31 20:20:59.3219357 +0800 CST m=-59.998053199
        2020-07-31 19:21:59.3219357 +0800 CST m=-3599.998053199
        2020-07-30 20:21:59.3219357 +0800 CST m=-86399.998053199
        2020-07-31 20:22:59.3219357 +0800 CST m=+60.001946801
        2020-07-31 21:21:59.3219357 +0800 CST m=+3600.001946801
        2020-08-01 20:21:59.3219357 +0800 CST m=+86400.001946801
      2. 相减(获取两个时间点相差的时间):
        package main
        import (
        "fmt"
        "time"
        )
        func main() {
        // Sub 计算两个时间差
        subM := now.Sub(m1)
        fmt.Println(subM.Minutes(), "分钟")
        sumH := now.Sub(h1)
        fmt.Println(sumH.Hours(), "小时")
        sumD := now.Sub(d1)
        fmt.Printf("%v 天\n", sumD.Hours()/24)
        }
        // 输出
        1 分钟
        1 小时
        1
    6. 计时器:
      1. 一次性:
        package main
        import (
        "fmt"
        "time"
        )
        func main() {
        fmt.Println(time.Now().Second())  // 输出 6
        timer := time.NewTimer(time.Second * 3)  // 计时 3秒
        <- timer.C
        fmt.Println(time.Now().Second())  // 输出 9
        }
      2. 周期性:
        package main
        import (
        "fmt"
        "time"
        )
        func main() {
        ticker := time.NewTicker(time.Second * 1)
        i := 0
        for {
        <- ticker.C
        fmt.Println(time.Now().Second())
        i++
        if i == 3 {
         ticker.Stop() // 停止定时器
         break
        }
        }
        }
        // 输出
        13
        14
        15
  7. net —WEB处理:
    1. net/url —URL处理:
      1. URL 编/解码:
        package main
        import (
        "fmt"
        "net/url"
        )
        func main()  {
        encoded := url.QueryEscape("http://www.baidu.com")
        fmt.Println(encoded)  // 输出 http%3A%2F%2Fwww.baidu.com
        decoded,_ := url.QueryUnescape(encoded)
        fmt.Println(decoded)  // 输出 http://www.baidu.com
        }
    2. URL 解析:
      package main
      import (
      "fmt"
      "net/url"
      )
      func main()  {
      url := url.URL{}
      r,_ := url.Parse("http://www.baidu.com/a/b?name=xiaoming#title")
      fmt.Println(r.Scheme)  // 输出 http
      fmt.Println(r.Host)  // 输出 www.baidu.com
      fmt.Println(r.Path)  // 输出 /a/b
      fmt.Println(r.RawQuery)  // 输出 name=xiaoming
      fmt.Println(r.Fragment)  // 输出 title
      }
    3. 表单操作:
      package main
      import (
      "fmt"
      "net/url"
      )
      func main()  {
      form := url.Values{}
      // 添加
      form.Add("a","aa")
      form.Add("b","bb")
      form.Add("c","cc")
      // 修改
      form.Set("a","11")
      // 获取
      fmt.Println(form.Get("a"))  // 输出 11
      // 删除
      form.Del("b")
      // 格式化输出
      fmt.Println(form.Encode())  // 输出 a=11&c=cc
      }
    4. net/http —网络请求:
      1. GET 请求:
        package main
        import (
        "fmt"
        "io"
        "io/ioutil"
        "net/http"
        )
        func HTTP_GET(url string) string {
        resp, _ := http.Get(url)
        if resp.StatusCode == 200{
        var bodyReader io.ReadCloser = resp.Body
        body, _ := ioutil.ReadAll(bodyReader)
        return string(body)
        }else {
        return ""
        }
        }
        func main() {
        var url string = "http://httpbin.org/get?page=1&limit=2"
        ret := HTTP_GET(url)
        fmt.Println(ret)
        }
        // 输出
        {
        "args": {
        "limit": "2", 
        "page": "1"
        }, 
        "headers": {
        "Accept-Encoding": "gzip", 
        "Host": "httpbin.org", 
        "User-Agent": "Go-http-client/1.1", 
        "X-Amzn-Trace-Id": "Root=1-5eb89b8d-8c8ada7647099878a4a9a21e"
        }, 
        "origin": "110.54.153.6", 
        "url": "http://httpbin.org/get?page=1&limit=2"
        }
      2. POST 请求:
        package main
        import (
        "net/http"
        "fmt"
        "io/ioutil"
        "io"
        "net/url"
        )
        func HTTP_POST(url string,params url.Values) string {
        resp, _ := http.PostForm(url, params)
        fmt.Println(resp.StatusCode)  // 输出 200
        if resp.StatusCode == 200{
        var bodyReader io.ReadCloser = resp.Body
        body, _ := ioutil.ReadAll(bodyReader)
        return string(body)
        }else{
        return ""
        }
        }
        func main() {
        var apiURL string = "http://httpbin.org/post?page=1"
        var params url.Values = url.Values{"names[]": []string{"xiaoming", "xiaomei"}}
        params.Set("age", "20")
        ret := HTTP_POST(apiURL,params)
        fmt.Println(ret)
        }
        // 输出
        {
        "args": {
        "page": "1"
        }, 
        "data": "", 
        "files": {}, 
        "form": {
        "age": "20", 
        "names": [
        "xiaoming", 
        "xiaomei"
        ]
        }, 
        "headers": {
        "Accept-Encoding": "gzip", 
        "Content-Length": "35", 
        "Content-Type": "application/x-www-form-urlencoded", 
        "Host": "httpbin.org", 
        "User-Agent": "Go-http-client/1.1", 
        "X-Amzn-Trace-Id": "Root=1-5eb89c05-8b48bc9c15b8d368996b781c"
        }, 
        "json": null, 
        "origin": "110.54.153.6", 
        "url": "http://httpbin.org/post?page=1"
        }
      3. JSON/XML 请求:
        package main
        import (
        "net/http"
        "fmt"
        "io/ioutil"
        "strings"
        )
        func HTTP_JSON(url string,str string) string {
        // 创建客户端实例
        client := &http.Client{}
        // 创建请求实例
        req, _ := http.NewRequest("POST", url, strings.NewReader(str))
        // 增加Header
        req.Header.Add("Content-Type", "application/json")
        req.Header.Add("Content-Encoding", "gzip")
        // 发起请求
        resp, _ := client.Do(req)
        defer func() {
        _ = resp.Body.Close()
        }()
        body,_ := ioutil.ReadAll(resp.Body)
        return string(body)
        }
        func main() {
        var apiURL string = "http://httpbin.org/post?page=1"
        str := `
         {
             "name": "lee",
             "gender": "male"
         }
        `
        ret := HTTP_JSON(apiURL,str)
        fmt.Println(ret)
        }
        // 输出
        {
        "args": {
        "page": "1"
        },
        "data": "\n\t\t\t{\n\t\t\t\t\"name\": \"lee\",\n\t\t\t\t\"gender\": \"male\"\n\t\t\t}\n\t\t",
        "files": {},
        "form": {},
        "headers": {
        "Accept-Encoding": "gzip",
        "Content-Encoding": "gzip",
        "Content-Length": "53",
        "Content-Type": "application/json",
        "Host": "httpbin.org",
        "User-Agent": "Go-http-client/1.1",
        "X-Amzn-Trace-Id": "Root=1-5f127f39-62f99cf6a7d8778c27ac4f0a"
        },
        "json": {
        "gender": "male",
        "name": "lee"
        },
        "origin": "159.138.40.51",
        "url": "http://httpbin.org/post?page=1"
        }
      4. 原生请求:
        package main
        import (
        "net/http"
        "fmt"
        "io/ioutil"
        "net/url"
        "strings"
        )
        func main() {
        var apiURL string = "http://httpbin.org/post?page=1"
        var params url.Values = url.Values{}
        params.Set("name", "yujc")
        // 创建客户端实例
        client := &http.Client{}
        // 创建请求实例
        req, _ := http.NewRequest("POST", apiURL, strings.NewReader(params.Encode()))
        // 增加Header
        req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
        req.Header.Add("Content-Encoding", "gzip")
        // 发起请求
        resp, _ := client.Do(req)
        defer func() {
        _ = resp.Body.Close()
        }()
        body,_ := ioutil.ReadAll(resp.Body)
        //读取响应
        fmt.Println(string(body))
        }
        // 输出
        {
        "args": {
        "page": "1"
        }, 
        "data": "", 
        "files": {}, 
        "form": {
        "name": "yujc"
        }, 
        "headers": {
        "Accept-Encoding": "gzip", 
        "Content-Encoding": "gzip", 
        "Content-Length": "9", 
        "Content-Type": "application/x-www-form-urlencoded", 
        "Host": "httpbin.org", 
        "User-Agent": "Go-http-client/1.1", 
        "X-Amzn-Trace-Id": "Root=1-5eb89d22-c5e0c08be92c50445bf2b13c"
        }, 
        "json": null, 
        "origin": "110.54.153.6", 
        "url": "http://httpbin.org/post?page=1"
        }
      5. 静态文件处理:
        package main
        import "net/http"
        func main() {
        http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./statics"))))
        http.ListenAndServe(":8080", nil)
        }
    5. net/http/pprof —性能监控:
      package main
      import (
      "net/http"
      _ "net/http/pprof"
      )
      func main(){
      http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
       w.Write([]byte("ok"))
      })
      http.ListenAndServe(":8080", nil)
      }
      // 访问 http://localhost:8080/debug/pprof/
  8. os —目录/文件操作:
    1. 目录操作:
      package main
      import "os"
      func main()  {
      os.Mkdir("tmp", 0755)  // 创建目录
      os.MkdirAll("tmp/dir1/dir2", 0755)  // 递归创建
      os.Remove("tmp")  // 删除目录
      os.RemoveAll("tmp")  // 递归删除
      }
    2. 文件操作:
      1. 创建文件:
        package main
        import "os"
        func main()  {
        os.Create("test.txt")
        }
      2. 打开文件:
        package main
        import (
        "fmt"
        "os"
        )
        func main()  {
        fp,_ := os.OpenFile("test.txt",1,0644)
        fmt.Println(fp)  // 输出 &{0xc00001e1e0}
        }
      3. 写文件:
        package main
        import "os"
        func main()  {
        fp,_ := os.OpenFile("test.txt",2,0644)
        defer fp.Close()
        fp.WriteString("Just a test!\r\n")
        }
      4. 读文件:
        package main
        import (
        "fmt"
        "os"
        )
        func main() {
        fl, _ := os.Open("test.txt")
        defer fl.Close()
        buf := make([]byte, 1024)
        for {
        n, _ := fl.Read(buf)
        if 0 == n {
         break
        }
        fmt.Println(string(buf[:n]))
        }
        }
        // 输出
        Just a test!
      5. 删除文件:
        package main
        import "os"
        func main() {
        os.Remove("test.txt")
        }
  9. sort —切片排序:
    1. 正向排序:
      package main
      import (
      "fmt"
      "sort"
      )
      func main() {
      nums := []int{5,2,1,3,4}
      // sort.Float64s(floats)
      // sort.Strings(strings)
      sort.Ints(nums)
      fmt.Println(nums)  // 输出 [1 2 3 4 5]
      // 是否已排序
      fmt.Println(sort.IntsAreSorted(nums))  // 输出 true
      }
    2. 反向排序:
      package main
      import (
      "fmt"
      "sort"
      )
      func main() {
      nums := []int{5,2,1,3,4}
      reverse_nums := sort.Reverse(sort.IntSlice(nums))
      sort.Sort(reverse_nums)
      fmt.Println(nums)  // 输出 [5 4 3 2 1]
      }
  10. flag —获取命令行参数:
    -- test.go
    package main
    import (
    "flag"
    "fmt"
    "os"
    )
    func main() {
    a := flag.String("a", "", "参数a")
    b := flag.Bool("b", false, "参数b")
    flag.Parse()
    if *a == "" || *b == false {
        // 打印提示信息
        flag.PrintDefaults()
        os.Exit(1)
    }
    fmt.Println(*a)
    fmt.Println(*b)
    }
    // 运行 go run test.go -a xiaoming -b true
    // 输出
    xiaoming
    true
  11. fmt.printf —格式化输出:
    package main
    import (
    "fmt"
    )
    type myStruct struct {
    x, y int
    }
    func main() {
    s := myStruct{1, 2}
    // 结构体
    fmt.Printf("%v \n", s)  // {1 2}
    fmt.Printf("%+v \n", s)  // {x:1 y:2}
    fmt.Printf("%#v \n", s)  // main.myStruct{x:1, y:2}
    fmt.Printf("%T \n", s)  // main.myStruct
    // 布尔值
    fmt.Printf("%t \n", true)
    // 整型
    fmt.Printf("%d \n", 123) // 123
    fmt.Printf("%b \n", 14)  // 1110(二进制)
    fmt.Printf("%c \n", 33)  // !(ASCII 码)
    fmt.Printf("%x \n", 456)  // 1c8(十六进制)
    // 浮点型
    fmt.Printf("%f \n", 78.9)  // 78.900000
    fmt.Printf("%e \n", 123400000.0)  // 1.234000e+08
    fmt.Printf("%E \n", 123400000.0)  // 1.234000E+08
    // 字符串型
    fmt.Printf("%s \n", `"string"`)  // "string"
    fmt.Printf("%q \n", `"string"`)  // "\"string\""
    // 指针类型
    fmt.Printf("%p \n", &s)  // 0xc000014070
    // 格式化输出(整型)
    fmt.Printf("|%6d|%6d| \n", 12, 345)              // |    12|   345|
    // 格式化输出(浮点型)
    fmt.Printf("|%6.2f|%6.2f| \n", 1.2, 3.45)          // |  1.20|  3.45|(右对齐)
    fmt.Printf("|%-6.2f|%-6.2f| \n", 1.2, 3.45)     // |1.20  |3.45  |(左对齐)
    // 格式化输出(字符串型)
    fmt.Printf("|%6s|%6s| \n", "foo", "b")            // |   foo|     b|
    fmt.Printf("|%-6s|%-6s| \n", "foo", "b")        // |foo   |b     |
    }
  12. 编译/运行命令:
    1. 编译:
      go build *.go
      或
      go build .
    2. 运行:
      go run *.go
      或
      go run .
    3. 交叉编译:
      1. linux 系统:
        # linux -> mac
        CGO_ENABLED=0
        GOOS=darwin
        GOARCH=amd64
        go build main.go
        # linux -> windows
        CGO_ENABLED=0
        GOOS=windows
        GOARCH=amd64
        go build main.go
      2. mac 系统:
        # mac -> linux
        CGO_ENABLED=0
        GOOS=linux
        GOARCH=amd64
        go build main.go
        # mac -> windows
        CGO_ENABLED=0
        GOOS=windows
        GOARCH=amd64
        go build main.go
      3. windows 系统:
        # windows -> mac
        SET CGO_ENABLED=0
        SET GOOS=darwin
        SET GOARCH=amd64
        go build main.go
        # windows -> linux
        SET CGO_ENABLED=0
        SET GOOS=linux
        SET GOARCH=amd64
        go build main.go
  13. sync —GO 协程同步:
    1. sync.WaitGroup —计数器(结束单个协程):
      package main
      import (
      "fmt"
      "sync"
      )
      func main() {
      wg := sync.WaitGroup{}
      wg.Add(3)
      for i := 0; i < 3; i++ {
       go func(i int,wg *sync.WaitGroup) {
           fmt.Println(i)
           wg.Done()
       }(i,&wg)
      }
      wg.Wait()
      }
      // 输出
      2
      0
      1
    2. sync.Mutex —线程锁:
      package main
      import (
      "fmt"
      "sync"
      "time"
      )
      func main() {
      wg := sync.Mutex{}
      for i := 0; i < 3; i++ {
       go func(i int,wg *sync.Mutex) {
           wg.Lock()
           defer wg.Unlock()
           fmt.Println(i)
       }(i,&wg)
      }
      time.Sleep(time.Second)
      }
      // 输出
      0
      2
      1
  14. go routine —协程:
    1. range + close组合 —单 channel(结束所有协程):
      package main
      import (
      "fmt"
      )
      func main() {
      c := make(chan int)
      for j := 0;j < 3;j ++ {
       go func() {
           for i := 0;i < 3;i ++ {
               c <- i  // todo: 在协程函数中 push数据到 channel 中
           }
           close(c)
       }()
      }
      for i := range c{
       fmt.Println(i)  // todo: 在外部消耗 channel
      }
      }
      // 输出
      0
      1
      0
      0
      1
      2
    2. select —多 channel(结束所有协程):
      package main
      import (
      "fmt"
      )
      func main() {
      run := make(chan int)
      quit := make(chan string)
      for i := 0;i < 10;i ++{
       go func(i int) {
           run <- i
           if i == 1{
               quit <- "yes, I quited!"
           }
       }(i)
      }
      for{
       select {
       case <- run:
           fmt.Println("running")  // todo: 在外部消耗 channel
       case <- quit:
           fmt.Println("quited")
           return
           // case <- time.After(5 * time.Second):  // 超时
           // return
       }
      }
      }
      // 输出
      running
      running
      running
      quited
    3. chan —多线程阻塞:
      package main
      import "fmt"
      func main() {
      c := make(chan int)  // 创建
      for i := 0;i < 10;i ++{
       go func(i int) {
           fmt.Println(i)
       }(i)
      }
      <- c  // 消耗
      }
      // 输出
      1
      2
      3
      ...
    4. chan —多线程阻塞(指定个数,同 sync.WaitGroup):
      package main
      import (
      "fmt"
      )
      func main() {
      c := make(chan int)
      for i := 0; i < 10; i++ {
       go func(i int){
           fmt.Println("你好, 世界")
           c <- i
       }(i)
      }
      for i := 0; i < 10; i++ {  // 等待 10个后台线程完成
       <-c
      }
      }
      // 输出
      4
      9
      5
      6
      7
      8
      2
      1
      0
      3
    5. slice -消耗切片中的任务(指定 go程数量,回调函数):
      package main
      import (
      "fmt"
      "math"
      "sync"
      )
      /*
      * 开 go 程,消耗切片中的任务
      * @param s 切片
      * @param num go 程数量
      * @param f 回调函数
      */
      func SliceGo(s []interface{}, num int,f func(v interface{}))  {
      wg := sync.WaitGroup{}
      wg.Add(num)
      _len := len(s)
      one := math.Floor(float64(_len / num))
      for i := 0;i < num;i ++{
       start := i * int(one)
       one_s := []interface{}{}
       if i < num - 1{
           end := (i + 1) * int(one)
           one_s = s[start:end]
       }else {
           one_s = s[start:]
       }
       go func() {
           for _,v := range one_s{
               f(v)
           }
           wg.Done()
       }()
      }
      wg.Wait()
      }
      func main() {
      num := 6
      s := []interface{}{1,2,3,4,5,6,7,8,9,10,11,12,13}
      // 调用
      SliceGo(s,num, func(v interface{}) {
       fmt.Println(v)
      })
      }
      // 输出
      11
      12
      13
      9
      10
      3
      4
      7
      8
      1
      2
      5
      6
文档更新时间: 2020-08-07 18:49   作者:lee