Skip to content

Commit 071f707

Browse files
use encoder to make sane/DRY string/buffer usage in printing and writing cache
1 parent 1a38593 commit 071f707

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

main.go

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"bytes"
45
"context"
56
"crypto/md5"
67
"encoding/hex"
@@ -126,12 +127,14 @@ func main(){
126127
func writeCachedFile(awsSsoCachePath, awsSSOProfileName string, credentialProcessJson CredentialProcessJson) error {
127128
cachedFileName := getCachedFileName(awsSSOProfileName)
128129
cachedFilePath := filepath.Join(awsSsoCachePath, cachedFileName)
129-
130-
prettyJson, err := json.MarshalIndent(credentialProcessJson, "", " ")
130+
buffer, err := jsonEncode(credentialProcessJson)
131131
if err != nil {
132132
return err
133133
}
134-
err = ioutil.WriteFile(cachedFilePath, prettyJson, 0600)
134+
if err != nil {
135+
return err
136+
}
137+
err = ioutil.WriteFile(cachedFilePath, buffer.Bytes(), 0600)
135138
if err != nil {
136139
return err
137140
}
@@ -170,14 +173,23 @@ func getCachedFileName(awsSSOProfileName string) string {
170173
}
171174

172175
func printProfile(credentialProcessJson CredentialProcessJson) {
173-
prettyJson, err := json.MarshalIndent(credentialProcessJson, "", " ")
176+
buffer, err := jsonEncode(credentialProcessJson)
174177
if err != nil {
175-
log.Fatal().Err(err).Msg("marshalling json exploded")
178+
log.Fatal().Err(err).Msg("encoding json exploded")
176179
}
177-
178-
fmt.Println(string(prettyJson))
180+
fmt.Printf("%s", buffer.String())
179181
}
180182

183+
func jsonEncode(credentialProcessJson CredentialProcessJson) (*bytes.Buffer, error) {
184+
buffer := new(bytes.Buffer)
185+
encoder := json.NewEncoder(buffer)
186+
encoder.SetIndent("", " ")
187+
err := encoder.Encode(credentialProcessJson)
188+
if err != nil {
189+
return nil, err
190+
}
191+
return buffer, nil
192+
}
181193

182194
func getSsoRoleCredentials(profile Profile, awsSSOCredential AWSSSOCredential) (CredentialProcessJson, error) {
183195

0 commit comments

Comments
 (0)