feat: integrate cobra+viper into the app

This commit is contained in:
Muyao CHEN
2024-10-01 21:43:44 +02:00
parent b755bd0e23
commit 3d1d40b4fc
8 changed files with 191 additions and 13 deletions

View File

@ -0,0 +1,71 @@
// MIT License
//
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package howmuch
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
defaultConfigName = "howmuch"
homeConfigFolder = ".howmuch"
envPrevfix = "HOWMUCH"
configType = "yaml"
)
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.AddConfigPath(filepath.Join(home, homeConfigFolder))
viper.AddConfigPath(".")
viper.SetConfigType(configType)
viper.SetConfigName(defaultConfigName)
}
viper.AutomaticEnv() // read in environment variables that match
viper.SetEnvPrefix(envPrevfix)
// replace . - to _ in the envvar
replacer := strings.NewReplacer(".", "_", "-", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
fmt.Fprintln(os.Stdout, "Using config file:", viper.ConfigFileUsed())
}

View File

@ -23,13 +23,17 @@
package howmuch
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
func errArgsForNoArgCommand(cmd string, args string) error {
return fmt.Errorf("%q does not take any argument, got %q", cmd, args)
}
@ -54,12 +58,30 @@ to share their expense of an event or a trip`,
},
SilenceUsage: true,
}
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.PersistentFlags().
StringVarP(&cfgFile, "config", "c", "", "path to config file. Default config if left empty")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
return rootCmd
}
func run() error {
fmt.Println("How much do I owe you?")
settings, _ := json.MarshalIndent(viper.AllSettings(), "", " ")
fmt.Println(string(settings))
fmt.Println(viper.GetString("db.username"))
r := gin.Default()
r.GET("/", func(ctx *gin.Context) {