Created
November 14, 2013 07:35
-
-
Save scottcagno/7462893 to your computer and use it in GitHub Desktop.
read and write tar files/archives
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "archive/tar" | |
| "encoding/json" | |
| "fmt" | |
| "io" | |
| "log" | |
| "os" | |
| ) | |
| // test dataset | |
| var data = map[string]interface{}{ | |
| "foo_1": map[string]interface{}{"id": 1, "prefix": "foo", "active": false, "link": []int{0, 2}}, | |
| "foo_2": map[string]interface{}{"id": 2, "prefix": "foo", "active": true, "link": []int{1, 3}}, | |
| "foo_3": map[string]interface{}{"id": 3, "prefix": "foo", "active": false, "link": []int{2, 4}}, | |
| "foo_4": map[string]interface{}{"id": 4, "prefix": "foo", "active": true, "link": []int{3, 5}}, | |
| "foo_5": map[string]interface{}{"id": 5, "prefix": "foo", "active": false, "link": []int{4}}, | |
| } | |
| // write tar | |
| func DumpTar(name string, dat map[string]interface{}) { | |
| fd, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755) | |
| if err != nil { | |
| log.Fatalln(err) | |
| } | |
| tw := tar.NewWriter(fd) | |
| for name, contents := range dat { | |
| body, err := json.MarshalIndent(contents, "", " ") | |
| if err != nil { | |
| log.Fatalln(err) | |
| } | |
| hdr := &tar.Header{ | |
| Name: name, | |
| Size: int64(len(body)), | |
| } | |
| if err := tw.WriteHeader(hdr); err != nil { | |
| log.Fatalln(err) | |
| } | |
| if _, err := tw.Write(body); err != nil { | |
| log.Fatalln(err) | |
| } | |
| } | |
| if err := tw.Close(); err != nil { | |
| log.Fatalln(err) | |
| } | |
| if err := fd.Close(); err != nil { | |
| log.Fatal(err) | |
| } | |
| } | |
| func LoadTar(name string) map[string]interface{} { | |
| fd, err := os.OpenFile(name, os.O_RDONLY, 0755) | |
| if err != nil { | |
| log.Fatalln(err) | |
| } | |
| tr := tar.NewReader(fd) | |
| var dat = make(map[string]interface{}) | |
| for { | |
| hdr, err := tr.Next() | |
| if err == io.EOF { | |
| break | |
| } else if err != nil { | |
| log.Fatalln(err) | |
| } | |
| var body interface{} | |
| if err := json.NewDecoder(tr).Decode(&body); err != nil { | |
| log.Fatalln(err) | |
| } | |
| dat[hdr.Name] = body | |
| } | |
| return dat | |
| } | |
| func main() { | |
| DumpTar("data.tar", data) | |
| fmt.Println("dump tar: complete") | |
| hmm := LoadTar("data.tar") | |
| fmt.Println("load tar: complete") | |
| fmt.Println(hmm["foo_3"]) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment