This commit is contained in:
2025-03-11 01:32:08 +02:00
commit d1163ec629
4 changed files with 108 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.idea

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/rdarius/boot-dev-blog-aggregator
go 1.23.6

81
internal/config/config.go Normal file
View File

@@ -0,0 +1,81 @@
package config
import (
"encoding/json"
"os"
"os/user"
)
const configFileName = ".gatorconfig.json"
type Config struct {
DbUrl string `json:"db_url"`
CurrentUserName string `json:"current_user_name"`
}
func Read() (Config, error) {
filePath, err := getConfigFilePath()
if err != nil {
return Config{}, err
}
// read file
data, err := os.ReadFile(filePath)
if err != nil {
return Config{}, err
}
cfg := Config{}
err = json.Unmarshal(data, &cfg)
return cfg, nil
}
func (config Config) SetUser() error {
usr, err := user.Current()
if err != nil {
return err
}
config.CurrentUserName = usr.Username
err = write(config)
if err != nil {
return err
}
return nil
}
func getConfigFilePath() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
return homeDir + "/" + configFileName, nil
}
func write(cfg Config) error {
filePath, err := getConfigFilePath()
if err != nil {
return err
}
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ") // For pretty printing
err = encoder.Encode(cfg)
if err != nil {
return err
}
return nil
}

23
main.go Normal file
View File

@@ -0,0 +1,23 @@
package main
import (
"fmt"
"github.com/rdarius/boot-dev-blog-aggregator/internal/config"
"log"
)
func main() {
cfg, err := config.Read()
if err != nil {
log.Fatal(err)
}
cfg.SetUser()
cfg2, err := config.Read()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", cfg2)
}