特殊语法
三个点…
GOLANG
1 2 3 4 5 6 7 8 9 10
|
func DefaultBot(prepares ...BotPreparer) *Bot {}
testChatRoom(prepares...)
test := []string{"1", "2", "3", "4"} test1 := test[0:1] test2 := append(test1, test[3:]...)
|
大括号{}
GOLANG
1 2
| url.Values{"mod": {"desktop"}}
|
指针
以下为 简单理解
GOLANG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
*a=*b
number := 1 numberP := &number fmt.Printf("number地址是%v,值是%v", numberP, *numberP) *numberP = 2
var number2P *int number2P = new(int) *number2P = 2 fmt.Printf("number2P地址是%v,值是%v", number2P, *number2P)
|
关键字
type
GOLANG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
type HandlerType string
func (w HandlerType) BaseHost() string { return "https://" + string(w) }
const ( SUCCESS HandlerType = "success" FAIL HandlerType = "fail" )
fmt.Println(HandlerType("fail") == FAIL)
|
defer
关闭资源的时候可以用该关键字
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
| f, err := os.Open("config.json") if err != nil { log.Fatalf("open config err: %v", err) return } defer f.Close()
j.lock.Lock() defer j.lock.Unlock()
func (s *Store) Set(key string, value int) { defer s.lockUnlock()() s.data[key] = value } func (s *Store) lockUnlock() func() { s.mutex.Lock() return func() { s.mutex.Unlock() }
|
nil
没有要传的值,可以传 nil
GOLANG
1 2 3
|
var _ MessageHandlerInterface = (*UserMessageHandler)(nil)
|
range
GOLANG
1 2 3 4 5
| var myStr []string = nil for key, value := range myStr { fmt.Println(key, value) }
|
容器
数组
GOLANG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| var arr = [2]string{} var arr = []string{"1", "2"} var arr = [...]string{"1", "2"}
arr := [3]string{"11", "21"} for key, value := range arr { fmt.Println(key, value) }
arrLength := len(arr)
arrLength := cap(arr)
test := make(map[string]interface{})
test1 := [2]map[string]interface{}{}
|
切片
切片不存储元素,只是对数组的引用
打印所有切片可以用 arr 和 arr[:]
切片可以动态扩容。
放 容量 就是 数组 ,不放 容量 就是 切片 。
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
| var slice1 []string
fmt.Println(slice1) fmt.Println(len(slice1)) fmt.Println(cap(slice1))
fmt.Println(slice1 == nil)
var slice2 = []string{"1", "2"}
const LENGTH = 3 const CAPACITY = 5 var slice3 = make([]string, LENGTH, CAPACITY) fmt.Println(slice2) fmt.Println(slice3)
slice2 = append(slice2, "asdf") fmt.Println(slice2)
arr := []string{"1", "2", "3"} arr1 := arr[1:2] arr1 = append(arr1, "asdf") fmt.Println(arr) fmt.Println(arr1)
var result = []string{"1", "2", "3", "4"}
result = append(result[0:1], result[2:]...) fmt.Println(result) fmt.Println(len(result)) fmt.Println(cap(result))
var result2 = []string{"1", "2", "3"} result2 = result2[0:0] fmt.Println(result2)
|
map
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
| var testMap map[keyType]valueType
testMap = map[string]string { "中国": "china", "美国": "America", }
CAPACITY := 2 testMap = make(map[string]string, CAPACITY)
for k := range testMap { fmt.Println(k) } for _, v := range testMap { fmt.Println(v) }
delete(testMap, "中国") fmt.Println(testMap)
testMap = map[string]string{}
testMap = map[string]interface{}{ "Code": 3, "FromUserName": "username", }
match := map[string]struct{}{ "k": {}, } result, ok1 := match["k"] if ok1 { fmt.Println("获取的数据为" + result) } else { fmt.Println("没有该键的数据") }
|
json
这里展示 json 与 结构体 的映射
GOLANG
1 2 3 4 5 6 7 8 9
| type Configuration struct { Key string `json:"key"` }
config := &Configuration{}
config.Key = "helllo"
|
xml
这里展示 xml 与 结构体 的映射
GOLANG
1 2 3
| type LoginInfo struct { Ret int `xml:"ret"` }
|
一些模块
常用函数
| 函数 |
相关说明 |
| len() |
获取数组长度 |
| append() |
给切片中添加元素。 使用方法可以 点击 查看 |
常用模块的解析
| 模块名 |
相关说明 |
跳转链接 |
| bufio |
用于流的处理 |
点击跳转 |
| bytes |
用作流和二进制数据处理 |
点击跳转 |
| context |
用于不同 goroutine 之间交换信息 |
点击跳转 |
| errors |
用作错误提示 |
点击跳转 |
| exec |
用于命令行的执行 |
点击跳转 |
| filepath |
文件路径相关处理 |
点击跳转 |
| fmt |
用于数据输出与格式化 |
点击跳转 |
| html |
用于 html 数据处理 |
点击跳转 |
| http |
用于 http 请求与响应处理 |
点击跳转 |
| io |
用于流的处理 |
点击跳转 |
| json |
用于 json 相关的处理 |
点击跳转 |
| log |
用于日志相关的输出 |
点击跳转 |
| os |
用于路径与文件相关的处理 |
点击跳转 |
| regexp |
用于正则的处理 |
点击跳转 |
| runtime |
用于操作系统相关信息获取 如系统类型 |
点击跳转 |
| sort |
排序相关 |
点击跳转 |
| strconv |
字符串与数字,bool等转换 |
点击跳转 |
| strings |
用于字符串相关处理 |
点击跳转 |
| sync |
并发处理模块 |
点击跳转 |
| time |
时间处理模块 |
点击跳转 |
| unsafe |
用于指针相关处理 |
点击跳转 |
| url |
用于 url 相关处理 |
点击跳转 |
| xml |
用于 xml 数据处理 |
点击跳转 |
bufio
bytes
GOLANG
1 2 3 4 5 6 7 8 9 10
| var c bytes.Buffer c.WriteString(str1) c.WriteString(str2) fmt.Println(c.String())
c.ReadFrom(resp.Body) fmt.Println(string(c.Bytes()))
result := bytes.NewBuffer(byteArr)
|
context
GOLANG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
ctx, cancel = context.WithCancel(context)
cancel()
context.Background()
context.Done()
|
errors
GOLANG
1 2 3 4 5 6
| var NetworkErr = errors.New("wechat network error")
errors.Is(err, NetworkErr)
errors.As(err, ret)
|
exec
GOLANG
1 2
| exec.Command(cmd, args...).Start()
|
filepath
fmt
GOLANG
1 2 3 4 5 6 7 8 9 10
| fmt.Println()
fmt.Printf()
fmt.Sprintf(format string, a ...interface{})
fmt.Fprintf(w io.Writer, format string, a ...interface{})
fmt.Errorf()
|
html
http
GOLANG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
http.MethodGet
http.DetectContentType(fileType)
req, err := http.NewRequest("POST", "https://www.teach-anything.com/api/generate", bytes.NewBuffer(requestData))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(req)
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
|
io
GOLANG
1 2
| io.Copy(writer, resp.Body)
|
json
GOLANG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
encoder := json.NewDecoder(f)
err = encoder.Decode(&config)
requestData, err := json.Marshal(requestBody)
responseBody := &ResponseBody{} err = json.Unmarshal(body, responseBody)
var buffer bytes.Buffer encoder := json.NewEncoder(&buffer)
encoder.SetEscapeHTML(false) err := encoder.Encode(structInfo)
data, _ := json.Marshal(structInfo) body := bytes.NewBuffer(data)
|
log
GOLANG
1 2 3 4 5
|
log.Fatalf("open config err: %v", err)
log.Printf("Received Group %v Text Msg : %v", group.NickName, msg.Content)
|
os
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
|
f, err := os.Open("文件名")
ApiKey := os.Getenv("ApiKey")
os.CreateTemp("/root/work/go-project/wechatbot/openwechat", "*.*")
os.Remove()
os.FileInfo
os.File
file.Read(arr)
file.Write(arr)
file.Seek(0, 0)
file.Truncate(0)
file.Name()
|
regexp
GOLANG
1 2 3 4 5 6 7 8
| uuidRegexp := regexp.MustCompile(`uuid = "(.*?)";`)
results := uuidRegexp.FindSubmatch(buffer.Bytes()) match = string(results[1])
results := uuidRegexp.FindAllStringSubmatch("-axxb-ab-",-1)
|
runtime
sort
strconv
GOLANG
1 2 3 4 5 6
| strconv.FormatInt(uin, 10)
strconv.Parse(str, 10, 8)
1e6
|
strings
GOLANG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
strings.ReplaceAll(str, oldStr, newStr)
strings.Replace(text, old, new, -1)
strings.TrimSpace(str)
strings.Trim(str, "\n")
strings.Join(strArr, "|")
strings.TrimPrefix(strArr, ".")
strings.Index(str, subStr)
|
sync
time
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
| time.Minute
time.Unix()
now.Format("2006-01-02 15:04:05")
time.Since(start)
time.Now()
time.NewTicker()
ticker.C for { select { case <-ticker.C: if err := h.bot.DumpHotReloadStorage(); err != nil { return err } case <-h.bot.Context().Done(): return nil } }
|
unsafe
GOLANG
1 2 3 4 5 6 7 8 9 10
| unsafe.Pointer()
tt := []byte{48} ttPtr := &tt result := (*string)(unsafe.Pointer(ttPtr)) fmt.Println(*result == "0")
unsafe.Sizeof(nunber)
|
url
GOLANG
1 2 3 4 5 6 7 8 9 10 11
| url.Parse()
url.ParseQuery()
url.Values{}
(url.Values).Encode()
(*url.URL).String()
|
xml
相关总结
一些函数
bytes.Buffer就是内存的字节数组,io.Reader读取的也是字节数组
结构体定义了键与类型,map可以放任意的键
reader读取流(字节流,字符流),将流转成需要的格式;writer写出流(字节流,字符流),将数据转成流写出
函数回调
GOLANG
1 2 3 4 5 6
|
type Bot struct { ScanCallBack func(body CheckLoginResponse) }
|