Created
November 22, 2021 20:28
-
-
Save justinschuldt/e3241c33166e996367d86fbd41ce354f to your computer and use it in GitHub Desktop.
Golang add key/value to json file
This file contains 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 ( | |
"encoding/json" | |
"log" | |
"os" | |
"sync" | |
) | |
type Exclude struct { | |
Exclude map[string]string `json:"exclude"` | |
} | |
func addToFile(file, key, value string, mu sync.RWMutex) { | |
mu.Lock() | |
fileData, _ := os.ReadFile(file) | |
excluded := Exclude{} | |
unmarshalErr := json.Unmarshal(fileData, &excluded) | |
if unmarshalErr != nil { | |
log.Fatalf("failed unmarshaling excludeFile %v", excludeFile) | |
} | |
// add value | |
excluded.Exclude[key] = value | |
// now Marshal it | |
excludedBytes, marshalErr := json.MarshalIndent(excluded, "", " ") | |
if marshalErr != nil { | |
log.Fatal("failed marshaling exluded json.") | |
} | |
writeErr := os.WriteFile(file, excludedBytes, 0666) | |
mu.Unlock() | |
if writeErr != nil { | |
log.Fatal("failed writing to file", err) | |
} | |
log.Println("done writing to file.") | |
} | |
func main() { | |
var fileMutex sync.RWMutex | |
file := "/home/justin/exclusions.json" | |
addToFile(file, "foo", "bar", fileMutex) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment