io.Writer 解析

簡介

io.Writer 跟 io.Reader 一樣,都是 Interface 類型,功能非常強大,在任何需要寫入數(shù)據(jù),處理數(shù)據(jù)流的地方,我們都應該盡可能使用這兩個類型的對象。

io.Writer 的原型:

type Writer interface {
    Write(p []byte) (n int, err error)
}

跟 io.Reader 類似,一個對象只要實現(xiàn)了 Write() 函數(shù),這個對象就自動成為 Writer 類型。

常見 Writer 類型

(1)文件操作
使用 os.Create() 創(chuàng)建文件時,會返回一個 os.File 對象,它是一個 struct,但是由于它實現(xiàn)了 Read() ,Write(),Closer() 等函數(shù),因此它同時也是 Reader, Writer, Closer 等類型。

type File struct {
    *file // os specific
}

func (f *File) Write(b []byte) (n int, err error) {
    if err := f.checkValid("write"); err != nil {
        return 0, err
    }
    n, e := f.write(b)
    if n < 0 {
        n = 0
    }
    if n != len(b) {
        err = io.ErrShortWrite
    }

    epipecheck(f, e)

    if e != nil {
        err = &PathError{"write", f.name, e}
    }
    return n, err
}

(2)bytes.Buffer
在 Go 語言中,string 類型是 immutable 的,因此它沒有對應的 Writer,也就是說不存在 strings.NewWriter(s) 這種函數(shù)。最好的替代方式就是使用 bytes.Buffer,因為它既是一個 Reader 也是一個 Writer,我們既可以往里面寫也可以往外讀。我們可以通過 buf.String() 得到 string 類型的數(shù)據(jù),也可以通過 buf.Bytes() 拿到 []byte 類型的數(shù)據(jù)。

下面的例子展示了我們通過 bytes.NewBufferString(s) 函數(shù),先在 buffer 中初始化一段 string,然后往里面 append 另外一段 string。

s := "Hello"
buf := bytes.NewBufferString(s)
s2 := "to be appended"
buf.WriteString(s2)   // 或者 fmt.Fprint(buf, s2)
fmt.Println("Final string:", buf.String())

(3)http.ResponseWriter
在使用 Go 語言進行 Web 開發(fā)時,http.ResponseWriter 是最基本的類型之一,它本身是一個 Interface 類,原型如下:

type ResponseWriter interface {
    Header() Header
    Write([]byte) (int, error)
    WriteHeader(int)
}

可見,它只申明了需要實現(xiàn)三個函數(shù),由于其要求了 Writer() 函數(shù),包含了 Writer 的要求,因此,任何是符合 ResponserWriter 的類型必然是 Writer 類型。

下面是一個http.ResponseWriter 最常見的使用場景和方法的:

一、直接調(diào)用 Write() 寫入一串 []byte

func helloHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/plain") 
    w.Write([]byte("Hello World"))
    return
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.ListenAndServe(":8080", nil)
}

這種方式跟創(chuàng)建文件時,直接往文件對象中寫入 []byte 是一樣的:

func main() {
    f, _:= os.Create("test.txt")
    if _, err = f.Write([]byte("Hello world")); err != nil {
            log.Fatal(err)
    }
    f.Close()
}

二、或者 使用 io.WriteStirng() 或者 fmt.Fprintf() 往 Writer 中寫入 string

func helloHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello world!")
        fmt.Fprintf(w, "Hello, World!")
}
func main() {
    http.HandleFunc("/", helloHandler)
    http.ListenAndServe(":8080", nil)
}

(4) hash.Hash
hash 包中申明了 Hash 這個 interface 接口,作為所有 hash 函數(shù)的公共接口。它也是一個 Writer,原型如下:

type Hash interface {
    // Write (via the embedded io.Writer interface) adds more data to the running hash.
    // It never returns an error.
    io.Writer

    // Sum appends the current hash to b and returns the resulting slice.
    // It does not change the underlying hash state.
    Sum(b []byte) []byte

    // Reset resets the Hash to its initial state.
    Reset()

    // Size returns the number of bytes Sum will return.
    Size() int

    // BlockSize returns the hash's underlying block size.
    // The Write method must be able to accept any amount
    // of data, but it may operate more efficiently if all writes
    // are a multiple of the block size.
    BlockSize() int
}

使用方式

import (
    "crypto/sha1"
)

func main() {
    passwordHash := sha1.New()
    io.WriteString(passwordHash, combination) // 或者直接 passwordHash.Write(combination)
    fmt.Printf("Password Hash : %x \n", passwordHash.Sum(nil))
}

(5) bufio
可以通過 bufio.NewWriter(r) 函數(shù)來把原 io.Writer 對象封裝成一個 bufio.Writer 對象,從而進行 buffered 讀寫。

package main

import (
    "bufio"
    "os"
)

func main() {
    f, _ := os.Create("file.txt")
    w := bufio.NewWriter(f) // Create a new writer.
    w.WriteString("ABC")  // Write a string to the file.
    w.Flush()
}

(6) gzip 壓縮

package main

import (
    "bufio"
    "compress/gzip"
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

func main() {
    // Open file on disk.
    name := "file.txt"
    f, _ := os.Open("C:\\programs\\" + name)

    // Create a Reader and use ReadAll to get all the bytes from the file.
    reader := bufio.NewReader(f)
    content, _ := ioutil.ReadAll(reader)

    // Replace txt extension with gz extension.
    name = strings.Replace(name, ".txt", ".gz", -1)

    f, _ = os.Create("C:\\programs\\" + name)

    w := gzip.NewWriter(f)
    w.Write(content)
    w.Close()
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容