- 运行
- 格式化字符串
- 文件
- Json
- 日志
- working directory is not part of a module
- HTTP
- call function in another file
- 全局变量初始化 RestClient declared but not used
- exit
- exported function GetDevices should have comment or be unexportedgo-lint
- comment on exported function GetDevices should be of the form
- struct field tag
json: "api"
not compatible with reflect.StructTag.Get: bad syntax for struct tag valuestructtag - 数组
- 定时器
- 端口监听
- Array
- Map
- List
- Split string
- String to int
- int to string
- Address to string
- Addr get port
- print bytes as hex
- cannot convert nil (untyped nil value) to
- 自定义异常
运行
$ go run main.go --filename xxx.go
格式化字符串
package main
import (
"fmt"
"os"
)
type point struct {
x, y int
}
func main() {
// Go提供了几种打印格式,用来格式化一般的Go值,例如
// 下面的%v打印了一个point结构体的对象的值
p := point{1, 2}
fmt.Printf("%v\n", p)
// 如果所格式化的值是一个结构体对象,那么`%+v`的格式化输出
// 将包括结构体的成员名称和值
fmt.Printf("%+v\n", p)
// `%#v`格式化输出将输出一个值的Go语法表示方式。
fmt.Printf("%#v\n", p)
// 使用`%T`来输出一个值的数据类型
fmt.Printf("%T\n", p)
// 格式化布尔型变量
fmt.Printf("%t\n", true)
// 有很多的方式可以格式化整型,使用`%d`是一种
// 标准的以10进制来输出整型的方式
fmt.Printf("%d\n", 123)
// 这种方式输出整型的二进制表示方式
fmt.Printf("%b\n", 14)
// 这里打印出该整型数值所对应的字符
fmt.Printf("%c\n", 33)
// 使用`%x`输出一个值的16进制表示方式
fmt.Printf("%x\n", 456)
// 浮点型数值也有几种格式化方法。最基本的一种是`%f`
fmt.Printf("%f\n", 78.9)
// `%e`和`%E`使用科学计数法来输出整型
fmt.Printf("%e\n", 123400000.0)
fmt.Printf("%E\n", 123400000.0)
// 使用`%s`输出基本的字符串
fmt.Printf("%s\n", "\"string\"")
// 输出像Go源码中那样带双引号的字符串,需使用`%q`
fmt.Printf("%q\n", "\"string\"")
// `%x`以16进制输出字符串,每个字符串的字节用两个字符输出
fmt.Printf("%x\n", "hex this")
// 使用`%p`输出一个指针的值
fmt.Printf("%p\n", &p)
// 当输出数字的时候,经常需要去控制输出的宽度和精度。
// 可以使用一个位于%后面的数字来控制输出的宽度,默认
// 情况下输出是右对齐的,左边加上空格
fmt.Printf("|%6d|%6d|\n", 12, 345)
// 你也可以指定浮点数的输出宽度,同时你还可以指定浮点数
// 的输出精度
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
// To left-justify, use the `-` flag.
fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)
// 你也可以指定输出字符串的宽度来保证它们输出对齐。默认
// 情况下,输出是右对齐的
fmt.Printf("|%6s|%6s|\n", "foo", "b")
// 为了使用左对齐你可以在宽度之前加上`-`号
fmt.Printf("|%-6s|%-6s|\n", "foo", "b")
// `Printf`函数的输出是输出到命令行`os.Stdout`的,你
// 可以用`Sprintf`来将格式化后的字符串赋值给一个变量
s := fmt.Sprintf("a %s", "string")
fmt.Println(s)
// 你也可以使用`Fprintf`来将格式化后的值输出到`io.Writers`
fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
文件
包
"io/ioutil"
读文本
if content, err = ioutil.ReadFile(filename); err != nil {
fmt.Println(err)
return
}
Json
包
"encoding/json"
序列化
data, _ := json.Marshal(p)
反序列化
json.Unmarshal([]byte(data), p)
日志
package main
import log "github.com/cihub/seelog"
func main() {
defer log.Flush()
log.Info("Hello from Seelog!")
}
日志输出文件
logger, err := log.LoggerFromConfigAsFile("seelog.xml")
if err != nil {
return err
}
log.ReplaceLogger(logger)
<seelog type="asynctimer" asyncinterval="5000000" minlevel="debug" maxlevel="error">
<exceptions>
<exception funcpattern="*main.test*Something*" minlevel="info"/>
<exception filepattern="*main.go" minlevel="error"/>
</exceptions>
<outputs formatid="main">
<console/>
<splitter formatid="format1">
<file path="log.log"/>
<file path="log2.log"/>
</splitter>
<splitter formatid="format2">
<file path="log3.log"/>
<file path="log4.log"/>
</splitter>
<rollingfile formatid="someformat" type="size" filename="./log/roll.log" maxsize="100" maxrolls="5" />
<buffered formatid="testlevels" size="10000" flushperiod="1000">
<file path="./log/bufFileFlush.log"/>
</buffered>
<filter levels="error">
<file path="./log/error.log"/>
<smtp senderaddress="noreply-notification-service@none.org"
sendername="Automatic notification service"
hostname="mail.none.org"
hostport="587"
username="nns"
password="123">
<recipient address="john-smith@none.com"/>
<recipient address="hans-meier@none.com"/>
</smtp>
<conn net="tcp4" addr="server.address:5514" tls="true" insecureskipverify="true" />
</filter>
</outputs>
<formats>
<format id="main" format="%Date(2006 Jan 02/3:04:05.000000000 PM MST) [%Level] %Msg%n"/>
<format id="someformat" format="%Ns [%Level] %Msg%n"/>
<format id="testlevels" format="%Level %Lev %LEVEL %LEV %l %Msg%n"/>
<format id="usetags" format="<msg>%Msg</time>"/>
<format id="format1" format="%Date/%Time [%LEV] %Msg%n"/>
<format id="format2" format="%File %FullPath %RelFile %Msg%n"/>
</formats>
</seelog>
working directory is not part of a module
I found the same issue before, and I sovled this issue, change environment variables, GO111MODULE
from on
to auto
go env -w GO111MODULE=auto
HTTP
https://github.com/go-resty/resty
go语言怎么区分包、文件、文件夹?
est1.go
package main
import (
L "./lib"
)
func main() {
L.Demo()
}
lib\test2.go
Put test2.go file in subfolder lib
package lib
import "fmt"
// This func must be Exported, Capitalized, and comment added.
func Demo() {
fmt.Println("HI")
}
call function in another file
https://stackoverflow.com/questions/14155122/how-to-call-function-from-another-file-in-go-language
Go Lang by default builds/runs only the mentioned file. To Link all files you need to specify the name of all files while running.
Run either of below two commands:
$go run test1.go test2.go. //order of file doesn't matter
$go run *.go
You should do similar thing, if you want to build them.
全局变量初始化 RestClient declared but not used
不要用 :=
赋值。
exit
os.Exit(1)
exported function GetDevices should have comment or be unexportedgo-lint
comment on exported function GetDevices should be of the form
struct field tag json: "api"
not compatible with reflect.StructTag.Get: bad syntax for struct tag valuestructtag
no space after comma
数组
长度:len(arr)
定时器
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Go Tickers Tutorial")
// this creates a new ticker which will
// `tick` every 1 second.
ticker := time.NewTicker(1 * time.Second)
// for every `tick` that our `ticker`
// emits, we print `tock`
for _ = range ticker.C {
fmt.Println("tock")
}
}
https://tutorialedge.net/golang/go-ticker-tutorial/
端口监听
https://ipfs.io/ipfs/QmfYeDhGH9bZzihBUDEQbCbTc5k5FZKURMUoUvfmc27BwL/socket/tcp_sockets.html
Array
https://tour.golang.org/moretypes/15
初始化
直接声明
添加元素
a = append(a, e)
get last element from array
s := a[len(a)-1] // C
删除元素
// Remove the element at index i from a.
copy(a[i:], a[i+1:]) // Shift a[i+1:] left one index.
a[len(a)-1] = "" // Erase last element (write zero value).
a = a[:len(a)-1] // Truncate slice.
Print array
Map
id 自增
clients[len(clients)] = xxx
List
https://golang.org/pkg/container/list/
Split string
string.split
String to int
strconv.Atoi(addr[1])
int to string
t := strconv.Itoa(123)
int to byte
Address to string
Seems just
strRemoteAddr = conn.RemoteAddr().String()
Addr get port
type Addr interface {
Network() string // name of the network (for example, "tcp", "udp")
String() string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
}
print bytes as hex
fmt.Sprintf("%x", h.Sum(nil))
cannot convert nil (untyped nil value) to
return Sensor{},
自定义异常
err1 := errors.New("math: square root of negative number")