[Golang] Save JSON Data in Directory


This post shows how to convert data to JSON format and save the data in the directory, and if the directory does not exist, it will be created first.

Souce Code

savelink.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// http://stackoverflow.com/questions/10510691/how-to-check-whether-a-file-or-directory-denoted-by-a-path-exists-in-golang
// http://stackoverflow.com/questions/14249467/os-mkdir-and-os-mkdirall-permission-value
// http://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go
package mylib

import (
	"net/url"
	"encoding/json"
	"os"
	"io/ioutil"
	"fmt"
	"log"
)

type LinkInfo struct {
	Title		string
	Link		string
}

func SaveLinkAsJson(l LinkInfo, dir string) {
	if _, err := os.Stat(dir); err != nil {
		if os.IsNotExist(err) {
			os.Mkdir(dir, 0755)
		} else {
			log.Println(err)
		}
	}

	path := fmt.Sprint(dir, url.QueryEscape(l.Link))
	os.Remove(path)

	b, err := json.Marshal(l)
	if err != nil { log.Println(err) }

	ioutil.WriteFile(path, b, 0644)
}

Test

savelink_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package mylib

import "testing"

func TestSaveLinkAsJson(t *testing.T) {
	l1 := LinkInfo{"Google", "https://www.google.com/"}
	l2 := LinkInfo{"DuckDuckGo", "https://duckduckgo.com/"}
	d := "./links/"
	t.Log(l1, d)
	SaveLinkAsJson(l1, d)
	t.Log(l2, d)
	SaveLinkAsJson(l2, d)
}

Tested on: Ubuntu Linux 14.10, Go 1.4.


References:

[1]go - How to check whether a file or directory denoted by a path exists in golang? - Stack Overflow
[2]go - os.MkDir and os.MkDirAll permission value? - Stack Overflow
[3]How to efficiently concatenate strings in Go? - Stack Overflow