7

[Golang] Save JSON Data in Directory

 3 years ago
source link: http://siongui.github.io/2015/03/28/go-save-json-data-in-directory/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

// 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)
}

savelink_test.go | repository | view raw

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK