lasso/cmd/lasso/cmd/root.go

92 lines
2.5 KiB
Go

/*
Copyright © 2021 Arsen Musayelyan
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"fmt"
"net/http"
"strings"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/vmihailenco/msgpack/v5"
"go.arsenm.dev/lasso/internal/types"
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "lasso",
Short: "A brief description of your application",
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Config file path")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Search for config in config directory with name "lasso" (without extension).
viper.AddConfigPath("/etc/lasso")
viper.SetConfigType("toml")
viper.SetConfigName("lasso")
}
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("lasso")
viper.AutomaticEnv() // Read in environment variables that match
// If a config file is found, read it in.
viper.ReadInConfig()
}
// httpError logs an error as well as writing it to the HTTP response
func httpError(res http.ResponseWriter, statusCode int, err error, msg string) {
// Write status code
res.WriteHeader(statusCode)
var message string
if err != nil {
// Get message string containing error string
message = fmt.Sprintf("%s: %s", msg, err)
// Log error
log.Error().Err(err).Msg(msg)
} else {
// Set message string to given msg
message = msg
// Log message
log.Error().Msg(msg)
}
// Encode error response to HTTP response
msgpack.NewEncoder(res).Encode(types.Response{
Error: true,
Message: message,
})
}