Go 的一些常用记录

IDE not found sdk

修改 $GOPATH/src/runtime/internal/sys/zversion.go

1// Code generated by go tool dist; DO NOT EDIT.
2
3package sys
4
5const StackGuardMultiplierDefault = 1
6// 追加当前安装的版本
7const TheVersion = `go1.17.6`

代理

golang proxy setting

1export GOPROXY=https://goproxy.cn,https://mirrors.aliyun.com/goproxy,direct

env

1export GO111MODULE=auto
2export GOPROXY=https://goproxy.cn,direct
3export GOPATH=/Users/${USER}/go
4export GOBIN=$GOPATH/bin
5export PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin:$GOBIN:.

build

main.go

1package main
2
3import (
4	"os"
5	_ "gitea.linuxcrypt.cn/cli/version"
6)
7
8func main() {
9}

version/version.go

 1package version
 2
 3import "fmt"
 4
 5var (
 6	BUILD_VERSION string
 7	BUILD_DATE    string
 8	COMMIT_SHA1   string
 9)
10
11func init() {
12	fmt.Printf("BUILD_VERSION: %s, BUILD_DATE: %s, COMMIT_SHA1: %s\n", BUILD_VERSION, BUILD_DATE, BUILD_DATE)
13}

build

1go build -ldflags "-X gitea.linuxcrypt.cn/cli/version.BUILD_VERSION=0.0.1 -X gitea.linuxcrypt.cn/cli/version.BUILD_DATE=2023-01-04 -X gitea.linuxcrypt.cn/cli/version.COMMIT_SHA1=abc" -o ./bin/cli

输入-ldflags参数 ./bin/cli

 1BUILD_VERSION: 0.0.1, BUILD_DATE: 2023-01-04, COMMIT_SHA1: 2023-01-04
 2NAME:
 3   cli - CLI
 4
 5USAGE:
 6   cli [global options] [arguments...]
 7
 8VERSION:
 9   0.0.1
10
11GLOBAL OPTIONS:
12   --config value  (default: "config.yaml")
13   --help, -h      show help (default: false)
14   --version, -v   print the version (default: false)

http PostFromValue & r.Body

 1type RequestBody struct {
 2    Source string `json:"source"`
 3}
 4
 5// 监控处理
 6func handle(w http.ResponseWriter, r *http.Request) {
 7	key:= r.PostFormValue("key")
 8	var requestBody RequestBody
 9	b , err := io.ReadAll(r.Body)
10	defer r.Body.Close()
11	json.Unmarshal(b, &requestBody)
12}
13
14http.HandleFunc("/", handle)
15http.ListenAndServe(fmt.Sprintf("%s:%d", address, port), nil)

vscode debug & enable

11.文件>首选项>设置>搜索Test Flags
22.选择在settings.json中编辑
33.添加以下内容
4
5"go.testFlags":[
6      "-v"
7    ],

context 协程 关闭 Done

 1func TestContext(t *testing.T) {
 2    // 生成一个 可以取消的context
 3	bg, cancel := context.WithCancel(context.Background())
 4	defer cancel()
 5	go func(close context.CancelFunc) {
 6		time.Sleep(5 * time.Second)
 7		fmt.Println("sleep 5s.")
 8        // 5秒后  取消
 9		close()
10	}(cancel)
11
12	v := func(ctx context.Context) {
13		select {
14		case <-ctx.Done():
15            // 当5秒后取消,会进入当前
16			fmt.Println("Done")
17		case <-time.After(10 * time.Second):
18			fmt.Println("AFTER")
19		}
20        
21        // 执行后续流程
22		fmt.Println("task exit.")
23	}
24
25    // 启动协程
26	go v(bg)
27
28	fmt.Println("end time.")
29
30    // 主线程等待 20s
31	time.Sleep(20 * time.Second)
32/
33}

输出

1
2=== RUN   TestContext
3end time.
4sleep 5s.
5Done
6task exit.
7--- PASS: TestContext (20.00s)
8PASS
9ok  	github.com/clibing/essence-go/internal/spider	20.457s