Installation

WindowsMore

  • 下载并安装More
  • 配置环境变量:
GOARCH - amd64
GOROOT - D:\Softwares\Go\
GOOS   - windows
GOPATH - %USERPROFILE%\go

Mac OS

语法

Get last git tag as release version.

git describe --tags

deferMore

定义数组

files := []string{}
str[1 : 3] // 截取1,2共两个字符

APIs

strconv.Itoa(i) // int->string
os.Chdir(path) // 切换目录

$GOPATH

go编译后的二进制文件在$GOPATH/bin目录下

make

内置函数, 创建数组切片

eg:

myMap = make(map[string] PersonInfo, 100) # 个数100

map

key必须支持==(避免使用浮点型)value不做规范

map[key]value

init() functionMore

In Go, the init() function is incredibly powerful and compared to some other languages, is a lot easier to use within your Go programs. These init() functions can be used within a package block and regardless of how many times that package is imported, the init() function will only be called once.

##

COMMANDS

go build name.go
go install . # 编译,生成文件至$GOPATH/bin
go version
go get
go env
/Users/username/go/src/github.com # mac github目录

json.Marshal始终解析为{}

Cmd,Body需要大写

type StBody struct {
}

type Cmds struct {
	Cmd string `json:"cmd"`
	Body StBody `json:"body"`
}

emptyBody := StBody{}
cmdsJ := Cmds{Cmd : cmdlist, Body : emptyBody }

c, err := json.Marshal(cmdsJ)
if err != nil {
	log.Println("error:", err)
	return nil, err
}

log.Println("converted string:", string(c))

编写动态链接库dllMore,More2

test.dll

package main

import (
  "fmt"
  "C"
)

func main() {
  fmt.Printf("test")
}

//export Sum
func Sum(a int, b int) int {
    return a + b;
}

Compile to test.dll, will generate test.h and test.dll files.

invoke:

dll := syscall.NewLazyDLL("test.dll")
add := dll.NewProc("Sum")
ret, _, _ := add.Call(uintptr(1), uintptr(2))
println("1+1=", ret)

// go executable file can’t invoke test.dll writen by go directly.

编写plugin soMore

printtest.go

func PrintTest(strInput string) {
    fmt.Println("string in print.so is:", strInput)
}
p, err := plugin.Open("printtest.so")
if err != nil {
	panic(err)
}
f, err := p.Lookup("PrintTest")
if err != nil {
	panic(err)
}
f.(func(string))("hello go plugin")

FAQ

打印堆栈

"runtime/debug"

fmt.Printf("%s", debug.Stack())
debug.PrintStack()

module github.com/go-ini/ini: Get proxy.golang.org: dial tcp 172.217.163.49:443: i/o timeoutMore

go env -w GOPROXY=https://goproxy.cn
go env -w GOPROXY="https://goproxy.io"
go env -w GOPROXY=https://proxy.golang.org

若还是无效 启动一个新的terminal重试

Cgo enables the creation of Go packages that call C code.

use local packagesMore

project.go

package main

import "example.com/me/pretty"

func main() {
    pretty.Pretty("hi")
    pretty.Pretty([]int{1, 3, 5})
}

go.mod

module main

require example.com/me/pretty v0.0.0

replace example.com/me/pretty => ../pretty
example.com/me/pretty

二进制混淆More,More2

go与react native编写mobile appMore

ghostbridge

Move go dependency from $GOPATH to local vendorMore

export GO111MODULE=on
go mod init
go mod vendor # if you have vendor/ folder, will automatically integrate
go build

go mod private repoMore

git config --global url."https://${GITHUB_TOKEN}:x-oauth-basic@github.com/".insteadOf "https://github.com/"
[url "https://${36056978994a91128a4a4582f4fb346d34d7698b}:x-oauth-basic@github.com/"]
    insteadOf = https://github.com/

for windows:

input name and token in Credential Manager when prompting login.

for python:

-e git+http://pp:kmSU7Zyg9Apd6QT5Z5iS@git.domaon.com/groupname/projectname.git@develop#egg=groupname

build shared library

go build -buildmode=c-shared -o hello.dll -ldflags "-s -w"

PACKAGES

logrus - Structured, pluggable logging for Go.More

logrus.SetLevel(logrus.DebugLevel)
logrus.Debug("model init")

var logger = logrus.New()

gopm - 包管理工具More

gen - Converts a database into gorm structs and RESTful apiMore

crypto/aes - Go supplementary cryptography librariesMoreMore2

go-spew - Dump objectMore

Error

linux_syscall.c:67:13: error: implicit declaration of function 'setresgid' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
brew install FiloSottile/musl-cross/musl-cross

CGO_ENABLED=1 GOOS=linux GOARCH=amd64 CC=x86_64-linux-musl-gcc CXX=x86_64-linux-musl-g++ go build -o BIN_NAME

cannot find package “github.com …”

go get

https fetch failed: Get https://golang.org/x/crypto/scrypt?go-get=1

Fetching https://golang.org/x/crypto/scrypt?go-get=1
https fetch failed: Get https://golang.org/x/crypto/scrypt?go-get=1: dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected party did not properly respond after a peri
od of time, or established connection failed because connected host has failed to respond.
package golang.org/x/crypto/scrypt: unrecognized import path "golang.org/x/crypto/scrypt" (https fetch: Get https://golang.org/x/crypto/scrypt?go-get=1: dial tcp 216.239.37.1:443: connectex: A connect
ion attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
Fetching https://golang.org/x/net/html?go-get=1

Solution:

1.

cd C:\Users\Administrator\go\src\golang.org\x
git clone https://github.com/golang/crypto.git

you have to set system proxy and git proxy.

cannot find package “github.com/russross/blackfriday/v2”More

package github.com/russross/blackfriday/v2: cannot find package "github.com/russross/blackfriday/v2" in any of:
        D:\Softwares\Go\src\github.com\russross\blackfriday\v2 (from $GOROOT)
        C:\Users\Administrator\go\src\github.com\russross\blackfriday\v2 (from $GOPATH)

Solution: you should start a project with the Go module support before you can use it. This means that the directory where you run go get must have a go.mod file. Otherwise, you’re actually running the legacy go get.More

Error: Package "E:\\Projects\\smartcooly" not a go package or not in GOPATH.

xgo can’t load package: package .: no Go files

...
Compiling for android-16/arm...
can't load package: package .: no Go files in /
2019/04/24 00:47:03 Failed to cross compile package: exit status 1.

Solution: copy project to $GOPATH

Failed to connect to 127.0.0.1 port 3001: Connection refused

fatal: unable to access 'https://github.com/russross/blackfriday/': Failed to connect to 127.0.0.1 port 3001: Connection refused
package github.com/russross/blackfriday/v2: exit status 128

Solution: Use go but not xgo to cross platform compile.

go: cannot determine module path for source directory /Users/marstau/projects/ppp (outside GOPATH, no import comments)More

在 $GOPATH 之外使用 go modules,新项目需要加上模块名

go mod init git.domain.com/group/ppp

go: cannot determine module path for source directory

go: cannot determine module path for source directory E:\projects\pp (outside GOPATH, no import comments)

Solution:

set GO111MODULE=on
module git.marsta.com/group/project

遍历目录More

items, _ := ioutil.ReadDir(".")
  for _, item := range items {
      if item.IsDir() {
          subitems, _ := ioutil.ReadDir(item.Name())
          for _, subitem := range subitems {
              if !subitem.IsDir() {
                  // handle file there
                  fmt.Println("dir=" + item.Name() + "/" + subitem.Name())
              }
          }
      } else {
          // handle file there
          fmt.Println(item.Name())
      }
  }

golang cron定时任务MoreMore2More3More4

package main

import (
    "github.com/robfig/cron"
    "log"
)

func main() {
    i := 0
    c := cron.New()
    spec := "*/5 * * * * ?"
    c.AddFunc(spec, func() {
        i++
        log.Println("cron running:", i)
    })
    c.Start()
    
    select{}
}
每隔5秒执行一次:*/5 * * * * ?

每隔1分钟执行一次:0 */1 * * * ?

每天23点执行一次:0 0 23 * * ?

每天凌晨1点执行一次:0 0 1 * * ?

每月1号凌晨1点执行一次:0 0 1 1 * ?

在26分、29分、33分执行一次:0 26,29,33 * * * ?

每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?

2:59:59开始间隔2小时执行: 59 59 0/2 * * ?

不能使用: * * */1 * * 和 * * */1 * * ?

Go Libraries

Reference