8. 标准库(Go Tutorial)
来源:互联网 发布:读spring源码 编辑:程序博客网 时间:2024/05/22 12:28
标准库
- 1 文档与源代码
- 2 记录日志
- 3 编码解码
- 31 解码 json
- 32 编码 JSON
- 4 输入和输出
Go 标准库是一组核心包,用来扩展和增强语言的能力,会随着 Go 语言的升级而更新并保持向后兼容
8.1 文档与源代码
Go 语言的标准库里有超过 100 个包被分在了 38 个类别里面,详情请见Packages
8.2 记录日志
// This sample program demonstrates how to create customized loggers.package mainimport ( "io" "io/ioutil" "log" "os")var ( Trace *log.Logger // Just about anything Info *log.Logger // Important information Warning *log.Logger // Be concerned Error *log.Logger // Critical problem)func init() { file, err := os.OpenFile("errors.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { log.Fatalln("Failed to open error log file:", err) } Trace = log.New(ioutil.Discard, "TRACE: ", log.Ldate|log.Ltime|log.Lshortfile) Info = log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) Warning = log.New(os.Stdout, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile) Error = log.New(io.MultiWriter(file, os.Stderr), "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)}func main() { Trace.Println("I have something standard to say") Info.Println("Special Information") Warning.Println("There is something you need to know about") Error.Println("Something has failed")}
8.3 编码/解码
8.3.1 解码 json
// This sample program demonstrates how to decode a JSON response// using the json package and NewDecoder function.package mainimport ( "encoding/json" "fmt" "log" "net/http")type ( // gResult maps to the result document received from the search. gResult struct { GsearchResultClass string `json:"GsearchResultClass"` UnescapedURL string `json:"unescapedUrl"` URL string `json:"url"` VisibleURL string `json:"visibleUrl"` CacheURL string `json:"cacheUrl"` Title string `json:"title"` TitleNoFormatting string `json:"titleNoFormatting"` Content string `json:"content"` } // gResponse contains the top level document. gResponse struct { ResponseData struct { Results []gResult `json:"results"` } `json:"responseData"` })func main() { uri := "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=8&q=golang" // Issue the search against Google. resp, err := http.Get(uri) if err != nil { log.Println("ERROR:", err) return } defer resp.Body.Close() // Decode the JSON response into our struct type. var gr gResponse err = json.NewDecoder(resp.Body).Decode(&gr) if err != nil { log.Println("ERROR:", err) return } fmt.Println(gr) // Marshal the struct type into a pretty print // version of the JSON document. pretty, err := json.MarshalIndent(gr, "", " ") if err != nil { log.Println("ERROR:", err) return } fmt.Println(string(pretty))}
当需要处理的 JSON 文档以 string 的形式存在时,可以将 string 转换为 byte 切片([] byte),并使用 json 包的 Unmarshal 函数进行反序列化的处理
// This sample program demonstrates how to decode a JSON string.package mainimport ( "encoding/json" "fmt" "log")// Contact represents our JSON string.type Contact struct { Name string `json:"name"` Title string `json:"title"` Contact struct { Home string `json:"home"` Cell string `json:"cell"` } `json:"contact"`}// JSON contains a sample string to unmarshal.var JSON = `{ "name": "Gopher", "title": "programmer", "contact": { "home": "415.333.3333", "cell": "415.555.5555" }}`func main() { // Unmarshal the JSON string into our variable. var c Contact err := json.Unmarshal([]byte(JSON), &c) if err != nil { log.Println("ERROR:", err) return } fmt.Println(c)}
有时,无法为 JSON 的格式声明一个结构类型,而是需要更加灵活的方式来处理 JSON 文档
// This sample program demonstrates how to decode a JSON string.package mainimport ( "encoding/json" "fmt" "log")// JSON contains a sample string to unmarshal.var JSON = `{ "name": "Gopher", "title": "programmer", "contact": { "home": "415.333.3333", "cell": "415.555.5555" }}`func main() { // Unmarshal the JSON string into our map variable. var c map[string]interface{} err := json.Unmarshal([]byte(JSON), &c) if err != nil { log.Println("ERROR:", err) return } fmt.Println("Name:", c["name"]) fmt.Println("Title:", c["title"]) fmt.Println("Contact") fmt.Println("H:", c["contact"].(map[string]interface{})["home"]) fmt.Println("C:", c["contact"].(map[string]interface{})["cell"])}
8.3.2 编码 JSON
// This sample program demonstrates how to marshal a JSON string.package mainimport ( "encoding/json" "fmt" "log")func main() { // Create a map of key/value pairs. c := make(map[string]interface{}) c["name"] = "Gopher" c["title"] = "programmer" c["contact"] = map[string]interface{}{ "home": "415.333.3333", "cell": "415.555.5555", } // Marshal the map into a JSON string. data, err := json.MarshalIndent(c, "", " ") if err != nil { log.Println("ERROR:", err) return } fmt.Println(string(data))}
8.4 输入和输出
输出(Write 接口)
// Sample program to show how different functions from the// standard library use the io.Writer interface.package mainimport ( "bytes" "fmt" "os")// main is the entry point for the application.func main() { // Create a Buffer value and write a string to the buffer. // Using the Write method that implements io.Writer. var b bytes.Buffer b.Write([]byte("Hello ")) // Use Fprintf to concatenate a string to the Buffer. // Passing the address of a bytes.Buffer value for io.Writer. fmt.Fprintf(&b, "World!") // Write the content of the Buffer to the stdout device. // Passing the address of a os.File value for io.Writer. b.WriteTo(os.Stdout)}
// Sample program to show how to write a simple version of curl using// the io.Reader and io.Writer interface support.package mainimport ( "io" "log" "net/http" "os")// main is the entry point for the application.func main() { // r here is a response, and r.Body is an io.Reader. r, err := http.Get(os.Args[1]) if err != nil { log.Fatalln(err) } // Create a file to persist the response. file, err := os.Create(os.Args[2]) if err != nil { log.Fatalln(err) } defer file.Close() // Use MultiWriter so we can write to stdout and // a file on the same write operation. dest := io.MultiWriter(os.Stdout, file) // Read the response and write to both destinations. io.Copy(dest, r.Body) if err := r.Body.Close(); err != nil { log.Println(err) }}
阅读全文
0 0
- 8. 标准库(Go Tutorial)
- GO标准库概述
- GO语言标准库概览
- 1. Hello Go(Go Tutorial)
- Python 2.7 Tutorial —— 标准库
- go-database-sql-tutorial
- 6. 并发(Go Tutorial)
- Go语言标准库Json的使用.
- Go 语言标准库之 strings包
- Go 标准库介绍一: strings
- Go 标准库介绍二: time
- Go 标准库介绍三: os
- Go 标准库介绍四: path
- Go 标准库介绍五: io
- 7. 并发模式(Go Tutorial)
- Python 2.7 Tutorial —— 标准库II
- golang讲解(go语言)标准库分析之strings
- 一文读懂Go的net/http标准库
- 卷积神经网络Quiz2
- GDK和utf-8编码互相转换
- Centos 安装Sublime text 3
- ActiveMQ消息回流
- NSValue用法总结
- 8. 标准库(Go Tutorial)
- luogu P1096 Hanoi双塔问题
- RecyclerView实现带有头部的顶部悬浮置顶布局
- 大家好,第一次来,有个问题请教!
- Swift one
- 比特币源码解读一
- 1124. Raffle for Weibo Followers (20)
- java发送qq消息到指定qq
- Cassandra_维护和调优