欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

8. 标准库(Go Tutorial)

程序员文章站 2024-03-23 13:42:52
...

标准库

Go 标准库是一组核心包,用来扩展和增强语言的能力,会随着 Go 语言的升级而更新并保持向后兼容

8.1 文档与源代码

Go 语言的标准库里有超过 100 个包被分在了 38 个类别里面,详情请见Packages

8.2 记录日志

// This sample program demonstrates how to create customized loggers.
package main

import (
    "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 main

import (
    "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 main

import (
    "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 main

import (
    "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 main

import (
    "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 main

import (
    "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 main

import (
    "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)
    }
}
相关标签: golang