学习网址
https://studygolang.com/pkgdoc go标准库网站
https://blog.csdn.net/sanxiaxugang/article/details/60324012 strings库介绍
https://blog.csdn.net/wangshubo1989/article/details/70177928 bufio包介绍
http://www.01happy.com/golang-mysql-demo/ go 操作mysql示例
https://www.cnblogs.com/wdliu/p/9330278.html go操作redis和mysql
http://www.flysnow.org/2017/05/12/go-in-action-go-context.html go context详解
杂项条目
- 字符串字面量由双引号或者反引号(注意不是单引号) 来创建。如
"abc",`abc`
- go没有枚举类型,使用const
如:
type LineState int
// iota 初始化后会自动递增
const (
ReadCommonReuqest LineState = iota // value --> 0
ReadRespResult // value --> 1
GetParser // value --> 2
ReadCustomerLoginRequest // value --> 3
ReadClientLoginRequest
ReadNotify
ReadRelogin
ReadCustomerLogoutResp
ReadClientLogout
ReadWebResp
ReadWebLoginRequest
ReadCustomerLogoutRequest
ReadHeartBeat
)
- 变量批量声明
var a,b,c int
- fmt包提供了打印函数,可以将数据以字符串形式输出到控制台、文件、活着其他满足io.writer 接口的值以及字符串中
//如格式化输出字符串:
encyres := “abc”
httpstr := fmt.Sprintf("POST / HTTP/1.1
" +
"Host: 192.168.2.179:26311
" +
"User-Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows NT)
" +
"Accept-Encoding: gzip, deflate
" +
"Connection: Keep-Alive
" +
"content-type: Application/json;charset=utf-8
" +
"Cache-Control: no-cache
" +
"Content-Length: %d
%s",len(encyres),encyres)
-
使用strconv包来解决字符串转其他类型变量的问题
-
获取字符串长度 len([]rune(string))
-
go定时器
func demo() {
t1 := time.NewTimer(time.Second * 5)
t2 := time.NewTimer(time.Second * 10)
for {
select {
case <-t1.C:
println("5s timer")
t1.Reset(time.Second * 5)
case <-t2.C:
println("10s timer")
t2.Reset(time.Second * 10)
}
}
}
- string 和 []byte相互转换
//string 转为[]byte
var str string = "test"
var data []byte = []byte(str)
//byte转为string
var data [10]byte
byte[0] = 'T'
byte[1] = 'E'
var str string = string(data[:])
//获取字符串子串
index := strings.Index(line,"{")
fmt.Println(line[index:])
- 字符串比较是否相等
strings.Compare("GO","go" )
strings.EqualFold("GO","go") //不区分大小写
- bytes.Buffer 使用
一种byte类型的缓冲器 https://blog.csdn.net/txj236/article/details/52130439
- 按行读取文件
f, err := os.Open(file)
if err != nil {
panic(err)
}
defer f.Close()
rd := bufio.NewReader(f)
for {
line, err := rd.ReadString('
') //以'
'为结束符读入一行
if err != nil || io.EOF == err {
break;
}
}
- 预编译 正则表达式
/*预编译正则表达式*/
jsonre, _ = regexp.Compile("{.*}")
-
捕获匹配正则表达式的字符串
result_json_str := jsonre.FindString(line)
-
字符串替换
strings.Replace(str, "_", "-", -1) //-1表示替换所有,正数表示替换个数
-
声明无缓冲 通道
var done = make(chan int)
-
声明带缓冲通道
var sqlchan = make(chan string, 1000)
-
从json读取一个字段的值并进行转换,字段不存在或者转换错误还能给出默认值的函数
func GetJsonValueInt64(jsonbody *simplejson.Json, keyname string) int64 {
var value int64
valuestr, err := jsonbody.Get(keyname).String()
if err != nil {
fmt.Println(err.Error())
value = 0
} else {
value, err = strconv.ParseInt(valuestr, 10, 0)
if(err != nil){
value = 0
}
}
return value
}
- 定义一个预分配空间长度为0的切片(类似于C++中vector的reserve函数)
/*allocates an underlying array of size 10 and returns a slice of length 0 and capacity 10 that is backed by this underlying array.*/
make([]int, 0, 10)
- 判断一个通道是否被关闭的模型
//使用 for range 语句判断
func GetChan()(chan int){
var c = make(chan int)
go func() {
for num := range c{
fmt.Printf("Get num from Chane:%d
",num)
}
// 主线程关闭chan后会执行到这里
fmt.Println("chan is closed")
done <- 1
}()
return c
}
-
将int 转化为
string str := strconv.FormatInt(ressultcode,10))
-
interface与其它类型转换
func formatTimeStamp(in interface{}, layout string) (out string) {
timeStr := in.(int)
month, err := time.Parse(layout, string(timeStr))
if err != nil {
return time.Now().Format(layout)
}
return month.Format(layout)
}
-
查看某个变量的具体type
obj.(type)
-
接口类型转化
var user = map[string]interface{}{
"age": 30,
"address": "Beijing Tongzhou",
"married": true,
}
var age = user["age"].(int)
var address = user["address"].(string)
var married = user["married"].(bool)
- 命令行参数
使用os.Args
os.Args是一个字符串slice,长度可以用len(os.Args)来表示
if len(os.Args) < 6 {
fmt.Println("usage: --host=xxx --port=xxx --username=xxxx --passwd=xxx --dbname=xxxx")
return
}
for i := range os.Args{
fmt.Println(os.Args[i])
}
- for 是go语言里唯一的循环语句