登录
首页 >  Golang >  Go问答

问题:Golang 中对 xml 转 gzip 的处理有bug

来源:stackoverflow

时间:2024-02-28 14:39:24 186浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《问题:Golang 中对 xml 转 gzip 的处理有bug》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在开发一个使用 golang 将 xml 文件压缩为 gzip 的程序。

但程序无法生成文件,但是当我尝试将 .txt 文件转换为 gzip 时,它确实生成了输出。 这是我的程序:-

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "io"
    "log"
    "os"
)

type Notes struct {
    To      string `xml:"to"`
    From    string `xml:"from"`
    Heading string `xml:"heading"`
    Body    string `xml:"body"`
}

func main() {
    var buf bytes.Buffer
    zw := gzip.NewWriter(&buf)

    // Setting the Header fields is optional.
    zw.Name = "new.xml"

    _, err := zw.Write([]byte("Compressing"))
    if err != nil {
        log.Fatal(err)
    }

    if err := zw.Close(); err != nil {
        log.Fatal(err)
    }

    zr, err := gzip.NewReader(&buf)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Name: %s", zr.Name)

    if _, err := io.Copy(os.Stdout, zr); err != nil {
        log.Fatal(err)
    }

    if err := zr.Close(); err != nil {
        log.Fatal(err)
    }

}

我应该怎么做才能生成我想要的 .gz 文件。


解决方案


现在,zw.write() 调用会将(压缩的)数据写入 buff。相反,由于您想将其写入文件,因此您应该创建一些可以实现此目的的东西。

最简单的方法是使用 os.create()。该函数返回一个*os.file,它实现了io.writer

生成的代码将是这样的:

package main

import (
    "compress/gzip"
    "log"
    "os"
)

func main() {
    //  this creates a file and returns an implementation of io.writer
    filewriter, err := os.create("./file.gz")
    if err != nil {
        log.println(err)
        return
    }
    defer filewriter.close()

    //  use the io.writer to create the gzip.writer.
    zw := gzip.newwriter(filewriter)
    defer zw.close()

    // setting the header fields is optional.
    zw.name = "new.xml"

    //  when gzip.writer.write is called, it will pass on the data to the write func of the io.writer we passed on line 17.
    //  if there is an error writing to the actual file, it will be returned.
    _, err = zw.write([]byte("compressing"))
    if err != nil {
        log.println(err)
        return
    }
}

这种编写编写器的方式使得更改事物的工作方式变得非常容易,而无需更改大量代码。您可以更进一步,因为 *xml.encoder 也是 io.writer 的实现,它采用另一个 io.writer 作为参数,就像 *gzip.writer 一样。因此,要实际生成 xml 并将其写入文件并一路对其进行 gzip,您只需执行以下操作:

package main

import (
    "compress/gzip"
    "encoding/xml"
    "log"
    "os"
)

type Notes struct {
    To      string `xml:"to"`
    From    string `xml:"from"`
    Heading string `xml:"heading"`
    Body    string `xml:"body"`
}

func main() {
    //  This creates a file and returns *os.File, an implementation of io.Writer
    fileWriter, err := os.Create("./notes.gz")
    if err != nil {
        log.Println(err)
        return
    }
    defer fileWriter.Close()

    //  Use the io.Writer to create the gzip.Writer.
    zw := gzip.NewWriter(fileWriter)
    defer zw.Close()

    // Setting the Header fields is optional.
    zw.Name = "notes.xml"

    notes := []Notes{
        {
            To:      "Alice",
            From:    "Bob",
            Heading: "Hi",
            Body:    "Hey Alice, how are you?",
        },
        {
            To:      "Bob",
            From:    "Alice",
            Heading: "Re: Hi",
            Body:    "Hi Bob! I'm fine, thnx.",
        },
    }

    // Create the xml.Encoder, using the gzip.Writer (which implements io.Writer).
    xmlWriter := xml.NewEncoder(zw)
    // So now, we have an xml.Encoder which writes to a gzip.Writer which writes to io.File.

    // This call to Encode() will generate the XML, pass that to gzip.Writer.Write, which passes it to os.File.Write.
    err = xmlWriter.Encode(notes)
    if err != nil {
        log.Println(err)
        return
    }
}

这种写作者(以及读者)的写作方式非常强大。你可以在很多地方找到它,制作很容易“分层”作家。

理论要掌握,实操不能落!以上关于《问题:Golang 中对 xml 转 gzip 的处理有bug》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>