Home Golang 相关内容整合
Post
Cancel

Golang 相关内容整合

Golang 在windows下交叉编译

在1.8版本的环境下测试,只需 set GOARCH , set GOOS即可。即:

set GOARCH=386 (取决于linux处理器框架,命令:uname -a查看)
set GOOS=linux
go env (查看全局配置)

Golang反射包

利用反射包复制一个对象

1
2
3
4
obj := new(Object)

temp := reflect.New(reflect.ValueOf(obj).Elem().Type()).Interface()
obj2 := temp.(*Object)

obj是指针类型,

reflect.ValueOf(obj)是指针类型的反射值,

.Elem()是该指针指向的值得反射值,

.Type()是该反射值对应的类型

reflect.New(type)是创建一个新的该类型的值,并指向该值的指针的反射值,

.Interface()是返回该反射值对应的值(指针类型的值)

反射调用方法

1
2
3
4
5
6
7
8
mMethod := reflect.ValueOf(pointerValue).MethodByName(methodName)
var params []reflect.Value
params = make([]reflect.Value, length)
for i:= range params {
    //设置入参
    params[i] = reflect.ValueOf(...) 
}
mMethod.Call(params)

Golang 读取json文件

1
2
3
4
5
6
7
8
9
10
11
12
//打开文件
r, err := os.Open("config.json")    
if err != nil {
    log.Fatalln(err)
}
var conf Config
//解码JSON
decoder := json.NewDecoder(r)
err = decoder.Decode(&conf)    
if err != nil {
    log.Fatalln(err)
}

Golang Tcp Demo

Server:

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
package tcp

import (
       "net"
       "fmt"
)

func Listen() {
       listen,err := net.Listen("tcp",":12306")
       if err != nil {
              fmt.Println("listen error:",err.Error())
              return
       }

       for {
              conn ,err := listen.Accept()
              if err != nil {
                     fmt.Println("accept error:",err.Error())
                     continue
              }
              fmt.Println("accept,start read")
              go read(&conn)
       }
}

func read(conn *net.Conn) {
       for {
              var buffer []byte = make([]byte,128)
              fmt.Println("start read")
              i,err := (*conn).Read(buffer)
              fmt.Println("read length :",i)
              if err != nil {
                     fmt.Println("server read error:",err.Error())
                     break
              }
              if i > 0 {
                     fmt.Println("接收到数据:",string(buffer[0:i]))
              }
       }
}

client:

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
package tcp

import (
       "net"
       "fmt"
       "bytes"
)

func Connect() {
       conn,err := net.Dial("tcp","127.0.0.1:12306")
       if err != nil {
              fmt.Println("connect error:",err.Error())
       }
       write(&conn,"你好")
}

func write(conn *net.Conn,message string) {
       fmt.Println("start send message:",message)
       sendBytes := (*(bytes.NewBufferString(message))).Bytes()
       i,err := (*conn).Write(sendBytes)

       if err != nil {
              fmt.Println("client write error:",err.Error())
              return
       }

       if i != len(sendBytes) {
              fmt.Println("client write error")
              return
       }
}

Golang 常用方法记录

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
func POST(url string,params map[string]string,headers map[string]string) {
       do("POST", url, params, headers)
}

func GET(url string,params map[string]string,headers map[string]string) {
       do("GET", url, params, headers)
}

func do(method string,url string,params map[string]string,headers map[string]string) {
       var r http.Request
       r.ParseForm()
       for k,v := range params {
              r.Form.Add(k,v)
       }
       bodystr := strings.TrimSpace(r.Form.Encode())
       request, err := http.NewRequest(method,url,strings.NewReader(bodystr))

       if err != nil {
              println("error:",err.Error())
              return
       }
       for k,v := range headers {
              request.Header.Set(k,v)
       }

       var resp *http.Response
       resp, err2 := http.DefaultClient.Do(request)
       if err2 != nil {
              println("error:",err2.Error())
              return
       }

       defer resp.Body.Close()

       body, err3 := ioutil.ReadAll(resp.Body)
       if err3 != nil {
              println("error:",err3.Error())
              return
       }

       println(string(body))
}

func stringToBytes(value string) []byte {
       return bytes.NewBufferString(value).Bytes()
}

func bytesToString(value []byte) string {
       return bytes.NewBuffer(value).String()
}

func DesEncrypt(origData, key []byte) ([]byte, error) {
       block, err := des.NewCipher(key)
       if err != nil {
              return nil, err
       }
       origData = PKCS5Padding(origData, block.BlockSize())
       // origData = ZeroPadding(origData, block.BlockSize())
       blockMode := cipher.NewCBCEncrypter(block, key)
       crypted := make([]byte, len(origData))
       // 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
       // crypted := origData
       blockMode.CryptBlocks(crypted, origData)
       return crypted, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
       padding := blockSize - len(ciphertext)%blockSize
       padtext := bytes.Repeat([]byte{byte(padding)}, padding)
       return append(ciphertext, padtext...)
}

func DesDecrypt(crypted, key []byte) ([]byte, error) {
       block, err := des.NewCipher(key)
       if err != nil {
              return nil, err
       }
       blockMode := cipher.NewCBCDecrypter(block, key)
       origData := make([]byte, len(crypted))
       // origData := crypted
       blockMode.CryptBlocks(origData, crypted)
       origData = PKCS5UnPadding(origData)
       // origData = ZeroUnPadding(origData)
       return origData, nil
}

func PKCS5UnPadding(origData []byte) []byte {
       length := len(origData)
       // 去掉最后一个字节 unpadding 次
       unpadding := int(origData[length-1])
       return origData[:(length - unpadding)]
}
This post is licensed under CC BY 4.0 by the author.