Go Basics

Go Basics

基本语法

建议大家过一遍goexample的例子, 如果大家用emacs,可以org里面插入go代码,C-c C-c直接运行 出结果,非常方便哈

hello, world!

1
2
3
4
5
6
7
package main

import "fmt"

func main() {
        fmt.Println("Hello, World!")
}
Hello, World!

打印

打印对象

1
    log.Printf("%v", object)

变量

golang的变量类型有

基础类型

字符串string

字符串关键字string 两个字符串拼接可以相加

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
  package main

  import (
          "fmt"
          "reflect"
  )

  func main() {
          var a, b string
          a = "hello, "
          b = "liuliancao"
          fmt.Println(reflect.TypeOf(a+b))
          fmt.Println(a, b)
          fmt.Println(a+b)
          c, d  := "hello,", "liuliancao"
          fmt.Println(c, d)
  }
string
hello,  liuliancao
hello, liuliancao
hello, liuliancao
字符串替换
整数int

int8,int16,int32, int64, uint8, uint16, uint32, uint64等 整数常见的有移位,与&或|非^等操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
      package main
      import (
            "fmt"
    )
    func main() {
          var a int
          var b uint
          fmt.Println("int default is: ", a, "\nuint default is ", b)
          var is32, is64 bool
          fmt.Println("bool default is: ", is32)
          is32 = ^uint(0)>>32 == 0
          fmt.Println("is32: ", is32)
          is64 = ^uint(0)>>64 == 0
          fmt.Println("is64: ", is64)
          uintMax := ^uint(0)
          fmt.Println("uint max is: ", uintMax)
          intMax := int(^uint(0)>>1)
          fmt.Println("int max is: ", intMax)
  }
int default is:  0
uint default is  0
bool default is:  false
is32:  false
is64:  true
uint max is:  18446744073709551615
int max is:  9223372036854775807
浮点数float

float32或者float64

布尔值bool

true或者false,关键词bool

派生类型

指针pointer
数组array
结构体struct
channel类型
函数类型func
切片类型slice
接口类型interface
Map类型

类型转换

float to int

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  package main
  import(
          "fmt"
        "strconv"
  )

      func main(){
              var v float64 = 51
              fmt.Println(int(v))
              fmt.Println(string(int(v)))
              fmt.Println(strconv.Itoa(int(v)))
      }
51
3
51

string to float

1
  lot, _ := strconv.ParseFloat(ip_array[13], 32)

int to string

bytes to int

bytes to string

一般string,但是也可能出现问题

如果是数字,可以fmt.Sprintf("%x", variables)或者用hex.EncodeToString(variables)进行转换

json.Number to int

正则匹配

参考

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
  package main
  // regexp.Match
  // regexp.Match(pattern_string, b[]byte)(matched bool, err error)
  import (
      "regexp"
      "fmt"
  )
  func main() {
      s1 := []byte("hello, world!")
      s2 := []byte("  ")
      if matched, _ := regexp.Match("^\\s+$", s1); matched == true {
            fmt.Println(string(s1)+" match spaces")
      } else {
            fmt.Println(string(s1)+"not match spaces")
      }
      if matched, _ := regexp.Match("^\\s+$", s2); matched == true {
            fmt.Println(string(s2)+" match spaces")
      } else {
            fmt.Println(string(s2)+"not match spaces")
      }

  }
hello, world!not match spaces
   match spaces

注意下\s这种需要转义下

hello, world!not match spaces
   match spaces

文件相关

判断文件是否存在

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
  package main
  import (
        "fmt"
        "os"
  )
    func main() {
            p1 := "/Users/liuliancao/.vimrc"
            p2 := "/Users/liuliancao/.vimrc2"
            if _, err := os.Stat(p1); err == nil {
                  fmt.Println(p1+" exists.")
            } else {
                  fmt.Println(p1+" not exists.")
            }
            if _, err := os.Stat(p2); err == nil {
                  fmt.Println(p2+" exists.")
            } else {
                  fmt.Println(p2+" not exists.")
            }

      }
/Users/liuliancao/.vimrc exists.
/Users/liuliancao/.vimrc2 not exists.

文件读写

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
  package main

  import (
          "fmt"
          "os"
          "reflect"
          "io/ioutil"
  )

  func main() {
          f, err := os.Open("/tmp/test")
          if err != nil {
                  fmt.Println("os.Open('/tmp/test) error: "+err.Error())
          } else {
                  ioutil.WriteFile("/tmp/test", []byte("test go write."), 644)
                  t, _ := os.Open("/tmp/test")
                  fmt.Println(reflect.TypeOf(f), f)
                  fmt.Println(reflect.TypeOf(t), ioutil.ReadAll(t))
          }
  }

json相关

json simple type

参考goexample

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  package main
    import (
            "fmt"
            "encoding/json"
    )
    func main() {
        // bool json
        bool_test, _ := json.Marshal(true)
        fmt.Println(string(bool_test))
        // int json
        int_test, _ := json.Marshal(1)
        fmt.Println(string(int_test))
        //string json
        string_test, _ := json.Marshal("hello")
        fmt.Println(string(string_test))
        //slice json
        slc1 := []string{"this", "is", "test"}
        slc_test, _ := json.Marshal(slc1)
        fmt.Println(string(slc_test))
        //map json
        map1 := map[string]string{"a":"z","b":"y"}
        map_test, _ := json.Marshal(map1)
        fmt.Println(string(map_test))
    }
true
1
"hello"
["this","is","test"]
{"a":"z","b":"y"}

jsonlike str to json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
  package main
    import (
            "fmt"
            "encoding/json"
    )
    type Ret struct {
        data string `json:"data"`
        msg string `json:"msg"`
        code int `json:"code"`
    }

    func main() {
       str1 := `{"data":"1", "msg":"test", "code":200}`
       str2 := `{"data":"1", "msg":"test", "code":200}`
       var ret1 map[string]interface{}
       ret2 :=  Ret{}
       err1 := json.Unmarshal([]byte(str1), &ret1)
       err2 := json.Unmarshal([]byte(str2), &ret2)
       fmt.Println(ret1, err1)
       fmt.Println(ret2, err2)
    }
map[code:200 data:1 msg:test] <nil>
{  0} <nil>

json to json str

嵌套json

可以使用simplejson

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
        ret, _ := simplejson.NewJson([]byte(result))
        rows, err := ret.Get("data").Get("guarders").Array()
        if err != nil {
                log.Println("parse all guarders with err: ", err)
        }
        for _, row := range rows {
                if guarder, ok := row.(map[string]interface{}); ok {
                        fmt.Println(guarder["ip"])
                }
        }

或者定义struct和json.Unmarshal

网络相关

了解下net模块

获取本机所有ip

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  package main

  import (
          "fmt"
          "net"
          "strings"
  )

  func GetIPs() (private_ips []string, public_ips []string, err error) {
          private_ips = make([]string, 0)
          public_ips = make([]string, 0)

          ifaces, e := net.Interfaces()
          if e != nil {
                  return private_ips, public_ips, e
          }
          for _, iface := range ifaces {
                if iface.Flags&net.FlagUp == 0 {
                        continue
                }

                if iface.Flags&net.FlagLoopback != 0 {
                        continue
                }

                if strings.HasPrefix("docker", iface.Name) || strings.HasPrefix("VMware", iface.Name) {
                        continue
                }

                fmt.Println("iface name:", iface.Name, "\niface mac:", iface.HardwareAddr, "\niface flags", iface.Flags,"\n")
                ipaddrs, e := iface.Addrs()

                if e != nil {
                        return private_ips, public_ips, e
                }
                for _, addr := range ipaddrs {
                        ipstr := strings.Split(addr.String(), "/")[0]
                        ip := net.ParseIP(ipstr)
                        if ip.IsPrivate() {
                               private_ips =  append(private_ips, ip.String())
                        }
                }
          }
          fmt.Println(private_ips)
          fmt.Println("114.114.114.114 is private?", net.ParseIP("114.114.114.114").IsPrivate())
          fmt.Println("127.0.0.1 is private?", net.ParseIP("127.0.0.1").IsPrivate())
          fmt.Println("192.168.16.1 is private?", net.ParseIP("192.168.16.1").IsPrivate())

          return private_ips, public_ips, nil
  }

  func main(){
          GetIPs()
  }
iface name: ens33
iface mac: 00:0c:29:c4:38:b7
iface flags up|broadcast|multicast

[192.168.10.204]
114.114.114.114 is private? false
127.0.0.1 is private? false
192.168.16.1 is private? true

根据类似192.168.10.0/24获取ip和网段

泛型

建议学习下这篇文章

标准库

flag

flag一般用来做命令行参数解析工具,使用也比较简单哈