Golang内置常用包
strings 字符串函数
strconv 字符串转换Append 系列函数将整数等转换为字符串后,添加到现有的字节数组中。 package main import ( "fmt" "strconv" ) func main() { str := make([]byte,10) str = strconv.AppendInt(str,-1,10) str = strconv.AppendUint(str,1,10) //无符号 fmt.Println(string(str)) str = strconv.AppendFloat(str,3.14159,'f',2,32) fmt.Println(string(str)) str = strconv.AppendFloat(str,30.14159,'e',3,64) fmt.Println(string(str)) str = strconv.AppendBool(str,true) fmt.Println(string(str)) str = strconv.AppendQuote(str,"hello") fmt.Println(string(str)) str = strconv.AppendQuoteRune(str,97) //字符a对应的ascii码 fmt.Println(string(str)) } 输出: -11 -113.14 -113.143.014e+01 -113.143.014e+01true -113.143.014e+01true"hello" -113.143.014e+01true"hello"'a' 注: // 'b' (-ddddp±ddd,二进制指数) // 'e' (-d.dddde±dd,十进制指数) // 'E' (-d.ddddE±dd,十进制指数) // 'f' (-ddd.dddd,没有指数) // 'g' ('e':大指数,'f':其它情况) // 'G' ('E':大指数,'f':其它情况) // 如果格式标记为 'e','E'和'f',则 prec 表示小数点后的数字位数 // 如果格式标记为 'g','G',则 prec 表示总的数字位数(整数部分+小数部分) 3、 Format 系列函数把其他类型的转换为字符串。 package main import ( "fmt" "strconv" ) func main() { fmt.Println(strconv.FormatBool(true)) fmt.Println(strconv.FormatInt(1,10)) fmt.Println(strconv.FormatUint(1,10)) fmt.Println(strconv.FormatFloat(3.14159,32)) } 输出: true 1 1 3.14 Parse 系列函数将字符串转换为 bool float int uint类型的值,err指定是否转换成功。 package main import ( "fmt" "strconv" ) func main() { fmt.Println(strconv.ParseBool("true")) fmt.Println(strconv.ParseInt("100",10,0)) fmt.Println(strconv.Atoi("100")) // 通常使用这个函数,而不使用 ParseInt fmt.Println(strconv.ParseUint("100",0)) fmt.Println(strconv.ParseFloat("3.14159",32)) } 输出: true <nil> 100 <nil> 100 <nil> 100 <nil> 3.141590118408203 <nil> 注: Quote 系列函数1、 package main import ( "fmt" "strconv" ) func main() { fmt.Println(strconv.Quote(`hello go 语言n`)) fmt.Println(strconv.Quote("hello go 语言n")) fmt.Println(strconv.QuoteToASCII(`hello go 语言n`)) fmt.Println(strconv.QuoteRune(97)) fmt.Println(strconv.QuoteRuneToASCII(97)) } 输出: "hello go 语言n" "hello go 语言n" "hello go u8bedu8a00n" 'a' 'a' encodingencoding/json
解析JSON package main import ( "encoding/json" "fmt" ) type Employee struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` } type EmployeeSlice struct { Employees []Employee `json:"employees"` } func main() { str := `{"employees":[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"}]}` var res EmployeeSlice json.Unmarshal([]byte(str),&res) fmt.Println(res) fmt.Println(res.Employees[0].FirstName) } 输出: [{Bill Gates} {George Bush}]} Bill 生成JSON: package main import ( "encoding/json" "fmt" ) type Employee struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` } type EmployeeSlice struct { Employees []Employee `json:"employees"` } func main() { data := EmployeeSlice{[]Employee{ {FirstName:"Bill",LastName:"Gates"},{FirstName:"George",LastName:"Bush"},}} res,_ := json.Marshal(data) fmt.Println(string(res)) } 输出: {"employees":[{"firstName":"Bill","lastName":"Bush"}]} cryptomd5package main import ( "crypto/md5" //"io" "fmt" "encoding/hex" ) func main(){ h := md5.New() //io.WriteString(h,"123456") h.Write([]byte("123456")) cipherStr := h.Sum(nil) fmt.Println(cipherStr) //一个128bit的16字节byte数组 fmt.Println(hex.EncodeToString(cipherStr)) // 输出加密结果 } 运行输出: [225 10 220 57 73 186 89 171 190 86 224 87 242 15 136 62] e10adc3949ba59abbe56e057f20f883e 使用 除了 //import "crypto/sha256" h := sha256.New() io.WriteString(h,"123456") fmt.Printf("%x",h.Sum(nil)) //import "crypto/sha1" h := sha1.New() io.WriteString(h,h.Sum(nil)) base64package main import ( "encoding/base64" "fmt" ) // 编码 func base64Encode(str []byte) []byte { return []byte(base64.StdEncoding.EncodeToString(str)) } // 解码 func base64Decode(str []byte) ([]byte,error){ return base64.StdEncoding.DecodeString(string(str)) } func main(){ str := "hello" enc_str := base64Encode([]byte(str)) fmt.Println(enc_str) fmt.Println(string(enc_str)) dec_str,err := base64Decode(enc_str) if(err != nil){ fmt.Println(err.Error()) } fmt.Println(dec_str) fmt.Println(string(dec_str)) } 输出: [97 71 86 115 98 71 56 61] aGVsbG8= [104 101 108 108 111] hello AESnetnet/urlnet/http
get请求package main import ( "net/http" "fmt" "io/ioutil" "io" ) func main() { var url string = "http://httpbin.org/get?page=1&limit=2" resp,err := http.Get(url) if (err != nil) { fmt.Println(err.Error()) } fmt.Println(resp.Status) //200 ok fmt.Println(resp.StatusCode) //200 var bodyReader io.ReadCloser = resp.Body //返回的是io.Reader body,_ := ioutil.ReadAll(bodyReader) fmt.Println(string(body)) } 输出: 200 OK 200 { "args": { "limit": "2","page": "1" },"headers": { "Accept-Encoding": "gzip","Connection": "close","Host": "httpbin.org","User-Agent": "Go-http-client/1.1" },"origin": "221.217.54.202","url": "http://httpbin.org/get?page=1&limit=2" } post表单请求post表单请求使用 package main import ( "net/http" "fmt" "io/ioutil" "io" "net/url" ) func main() { var apiURL string = "http://httpbin.org/post?page=1" var params url.Values = url.Values{"names": []string{"yjc","yjc1"}} params.Set("age","20") resp,err := http.PostForm(apiURL,params) if (err != nil) { fmt.Println(err.Error()) } fmt.Println(resp.Status) //200 ok fmt.Println(resp.StatusCode) //200 var bodyReader io.ReadCloser = resp.Body //返回的是io.Reader body,_ := ioutil.ReadAll(bodyReader) fmt.Println(string(body)) } 输出: 200 OK 200 { "args": { "page": "1" },"data": "","files": {},"form": { "age": "20","names": [ "yjc","yjc1" ] },"Content-Length": "27","Content-Type": "application/x-www-form-urlencoded","json": null,"url": "http://httpbin.org/post?page=1" } 封装package tool import ( "io/ioutil" "net/http" "net/url" "fmt" ) // get 网络请求 func Get(apiURL string,params url.Values) (rs []byte,err error) { var Url *url.URL Url,err = url.Parse(apiURL) if err != nil { fmt.Printf("解析url错误:rn%v",err) return nil,err } //如果参数中有中文参数,这个方法会进行URLEncode Url.RawQuery = params.Encode() resp,err := http.Get(Url.String()) if err != nil { fmt.Println("err:",err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } // post 网络请求,params 是url.Values类型 func Post(apiURL string,err error) { resp,params) if err != nil { return nil,err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } net/http/pprof该包来做代码的性能监控。使用示例: package main import ( "net/http" _ "net/http/pprof" ) func main(){ //提供给负载均衡探活以及pprof调试 http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request) { w.Write([]byte("ok")) }) http.ListenAndServe(":10000",nil) } 运行之后,在浏览器打开 go http.ListenAndServe(":10000",nil) 如何启动 PProf 可视化界面?
下面以 方法一: go tool pprof -http=:8080 http://localhost:10000/debug/pprof/profile 方法二: go tool pprof http://localhost:10000/debug/pprof/profile 然后在交互式命令行输入 参考:Golang pprof详解 os文件操作的大多数函数都是在os包里面。 目录操作:
示例: package main import ( "os" "fmt" ) func main() { os.Mkdir("tmp",0755) os.MkdirAll("tmp/test/test2",0755) err := os.Remove("tmp") if err != nil{ fmt.Println(err) } os.RemoveAll("tmp") } 运行输出: remove tmp: The directory is not empty. 文件操作:
io/ioutilioutil包封装了一些实用的 I/O 函数,提供给外部使用的一共有1个变量,7个方法。
ioio包是为 IO 原语(I/O primitives)提供基本的接口。 golang的io包 - 刘地的个人空间 - 开源中国 flag用于获取命令行参数。 示例: package main import ( "flag" "fmt" ) func main() { backup_dir := flag.String("b","/home/default_dir","backup path") debug_mode := flag.Bool("d",false,"debug mode") flag.Parse() fmt.Println("backup_dir: ",*backup_dir) fmt.Println("debug_mode: ",*debug_mode) } golang之flag.String - hezhixiong - 博客园 syncsync.WaitGrouppackage main import ( "fmt" "time" ) func main(){ for i := 0; i < 100 ; i++{ go fmt.Println(i) } time.Sleep(time.Second) } 上面主线程为了等待 对于这种情况,go语言中有一个其他的工具 使用WaitGroup 将上述代码可以修改为: func main() { wg := sync.WaitGroup{} wg.Add(100) for i := 0; i < 100; i++ { go func(i int) { fmt.Println(i) wg.Done() }(i) } wg.Wait() } 详见:Golang sync.WaitGroup的用法 runtimeruntime/debug用于:
详见:go-runtime/debug (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |