Skip to content

Instantly share code, notes, and snippets.

@darron
Last active October 12, 2016 16:40
Show Gist options
  • Select an option

  • Save darron/ec5d1d636eb2d486438d053a3689c039 to your computer and use it in GitHub Desktop.

Select an option

Save darron/ec5d1d636eb2d486438d053a3689c039 to your computer and use it in GitHub Desktop.
Adjust a bunch of JSON files in a folder.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
)
// User struct stores user data.
type User struct {
Name string
ID int
Sshkey string
Shell string
Group string
}
var (
maxSize = int64(4096)
theDir = "/Users/darron/Desktop/files-for-golang"
newShell = "/bin/evilbash"
)
func getFiles() []string {
var finalList []string
files, err := ioutil.ReadDir(theDir)
if err != nil {
log.Fatal("Oh boy - something went wrong.")
}
// Get the details on each file.
for _, theFile := range files {
fileName := theFile.Name()
fileSize := theFile.Size()
if fileSize > maxSize {
log.Printf("File '%s' is too big: '%d'", fileName, fileSize)
continue
}
finalList = append(finalList, fileName)
}
return finalList
}
func rewriteFile(f string) {
filePath := fmt.Sprintf("%s/%s", theDir, f)
fileContents, err := ioutil.ReadFile(filePath)
if err != nil {
log.Println("There was an error reading the file.")
}
theUser := User{}
// For each file - encode to JSON data structure.
json.Unmarshal(fileContents, &theUser)
// Change the shell to newShell
theUser.Shell = newShell
// Convert back to a string.
newString, err := json.Marshal(&theUser)
if err != nil {
log.Print("There was an error with the new JSON.")
}
// Save updated json to each file.
fileWriteErr := ioutil.WriteFile(filePath, newString, os.FileMode(0640))
if fileWriteErr != nil {
log.Println("There was an error writing the file.")
}
}
func main() {
// Get all files.
files := getFiles()
// Rewrite them all.
for _, fileName := range files {
rewriteFile(fileName)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment