go知识重新整理

This commit is contained in:
Estom
2021-09-03 05:34:34 +08:00
parent 62309f856a
commit 1bad082e49
291 changed files with 29345 additions and 2 deletions

BIN
Go/gopkg/encoding/color.gob Normal file

Binary file not shown.

36
Go/gopkg/encoding/csv.go Normal file
View File

@@ -0,0 +1,36 @@
// Comma-Separated Values
// 逗号分割值文件
package main
import (
"encoding/csv"
"fmt"
"os"
"strings"
)
func main() {
// 单行读取
r := strings.NewReader("a,b,c")
csvR := csv.NewReader(r)
records, _ := csvR.Read()
fmt.Println(records) // [a b c]
// 全部读取
f, _ := os.Open("demo.csv")
csvR = csv.NewReader(f)
fmt.Println(csvR.ReadAll()) // [[...]]
// 单行写入
w := csv.NewWriter(os.Stdout)
_ = w.Write(records)
w.Flush() // a,b,c // 类 Flush() 函数将缓冲区的数据写入真实文件,勿忘
// 批量写入
strs := [][]string{{"x", "y", "z"}, {"X", "Y", "Z"}}
w.WriteAll(strs)
w.Flush()
// x,y,z
// X,Y,Z
}

View File

@@ -0,0 +1,4 @@
FIRST NAME ,LAST NAME,USERNAME ,PASSWORD ,EMAIL ADDRESS,PHONE NUMBER,PASSPORT,GROUPS,USERCODE,TITLE,ADDRESS 1 ,ADDRESS 2,CITY,STATE,ZIP
Frank,Riley,friley,changeme,friley@kanab.org,123-456-7890,3,"1,3",1040,Teacher,328 Innovation,Suite # 200 ,state college,PA,16803
Steve,Brannigan,sbrannigan,changeme,sbrannigan@kanab.org,123-456-7890,3,1,1041,Teacher,328 Innovation,Suite # 200 ,state college,PA,16803
Marie,Ambrose,mambrose,changeme,mambrose@kanab.org,123-456-7890,3,1,1042,Teacher,328 Innovation,Suite # 200 ,state college,PA,16803
1 FIRST NAME LAST NAME USERNAME PASSWORD EMAIL ADDRESS PHONE NUMBER PASSPORT GROUPS USERCODE TITLE ADDRESS 1 ADDRESS 2 CITY STATE ZIP
2 Frank Riley friley changeme friley@kanab.org 123-456-7890 3 1,3 1040 Teacher 328 Innovation Suite # 200 state college PA 16803
3 Steve Brannigan sbrannigan changeme sbrannigan@kanab.org 123-456-7890 3 1 1041 Teacher 328 Innovation Suite # 200 state college PA 16803
4 Marie Ambrose mambrose changeme mambrose@kanab.org 123-456-7890 3 1 1042 Teacher 328 Innovation Suite # 200 state college PA 16803

29
Go/gopkg/encoding/gob.go Normal file
View File

@@ -0,0 +1,29 @@
// go binary 二进制编码解码
// gob 的数据都是直接面向二进制的 Reader 和 Writer通过实例化后 encoder 和 decoder 来操作数据
package main
import (
"encoding/gob"
"fmt"
"os"
)
type Color struct {
Red int
Yellow int
Blue int
}
func main() {
colors := []Color{{0, 0, 0}, {255, 255, 255}}
f, _ := os.OpenFile("color.gob", os.O_CREATE|os.O_WRONLY, 0666)
defer f.Close()
enc := gob.NewEncoder(f) // 为 writer 创建一个二进制流的编码器
_ = enc.Encode(colors)
f, _ = os.Open("colors.gob")
dec := gob.NewDecoder(f)
var newColors []Color
fmt.Println(dec.Decode(&newColors)) // invalid argument // 单个 struct 可以,数组不行,暂时无解
}

82
Go/gopkg/encoding/json.go Normal file
View File

@@ -0,0 +1,82 @@
// json 包有面向字符串和 struct 的序列化与反序列化
// 还有面向字节流的编码器和解码器
// 最后还有 HTMLEscape
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Tags []string `json:"tags"`
}
func main() {
//
// 序列化
//
u := User{
Name: "pike",
Age: 60,
Tags: []string{"C", "C++", "Go"},
}
b, _ := json.Marshal(u) // JSON 序列化
fmt.Println(string(b)) // {"name":"pike","age":60,"tags":["C","C++","Go"]}
b, _ = json.MarshalIndent(u, "", " ") // struct + 缩进 -> []byte
var user User // 序列化与反序列化是针对 struct <-> []byte 而言的
_ = json.Unmarshal(b, &user) // JSON 反序列化
s := `{"name":"wuYin", "age":"20"}`
dst := bytes.NewBuffer(nil)
json.Indent(dst, []byte(s), "_", "++++") // []byte(s) + 缩进 -> buffer
fmt.Println(dst.String())
// {
// _++++"name": "wuYin",
// _++++"age": "20"
// _}
//
// 流式编码解码器
//
// decoder 是从流中按序列读取数据,不会识别除目标结构以外的其他字符 , // 此处的 , 是无法解析的
streamJSON := `{"name":"pike","age":20,"tags":["C","C++","Go"]}{"name":"ken","age":20,"tags":["C","C++","Go"]}`
// 指向输入流的流式编码器
dec := json.NewDecoder(strings.NewReader(streamJSON))
for {
var u User
err := dec.Decode(&u)
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err) // 遇到未知错误
}
fmt.Println(u)
}
// 指向输出流的流式编码器
enc := json.NewEncoder(os.Stdout)
if err := enc.Encode(u); err != nil {
fmt.Println(err)
}
//
// 格式化
//
// 专门针对 JSON 的 copy 操作
buff := bytes.NewBuffer(nil)
_ = json.Compact(buff, b)
fmt.Println(buff.String()) // 此处把 JSON 的缩进清除了
// 转义 < > &
s = `{"name":"<script>alert('f**k')</script>", "age:1&1"}`
json.HTMLEscape(buff, []byte(s))
fmt.Println(string(buff.Bytes())) // {"name":"\u003cscript\u003ealert('f**k')\u003c/script\u003e", "age:1\u00261"}
}

44
Go/gopkg/encoding/xml.go Normal file
View File

@@ -0,0 +1,44 @@
package main
import (
"encoding/xml"
"fmt"
"os"
)
type Loc struct {
Country string
Province string
}
type City struct {
Loc
ID int `xml:"-"` // 不输出
People int `xml:"people,omitempty"` // 值为空时不输出
Name string `xml:"name"`
}
func main() {
//
// 序列化
//
c := City{ID: 1, Name: "西安"}
c.Loc = Loc{"中国", "陕西"}
b, _ := xml.Marshal(c)
os.Stdout.Write(b) // <City><Country>中国</Country><Province>陕西</Province><name>西安</name></City>
fmt.Println()
b, _ = xml.MarshalIndent(c, "", " ")
fmt.Println(string(b))
// <City>
// <Country>中国</Country>
// <Province>陕西</Province>
// <name>西安</name>
// </City>
//
// 转义
//
s := `<x>233</x>` // 将字符串中的 xml 保留字符转义
xml.Escape(os.Stdout, []byte(s)) // &lt;x&gt;233&lt;/x&gt;
}