本文整理汇总了Golang中github.com/spf13/viper.GetString函数的典型用法代码示例。如果您正苦于以下问题:Golang GetString函数的具体用法?Golang GetString怎么用?Golang GetString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GetString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
pflag.Parse()
viper.SetConfigName("config")
viper.AddConfigPath(".")
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
if err := viper.ReadInConfig(); err != nil {
logrus.Fatal(err)
}
nick := viper.GetString("twitch.nick")
pass := viper.GetString("twitch.pass")
channels := viper.GetStringSlice("twitch.join")
dbFilename := viper.GetString("database.filename")
superusers := viper.GetStringSlice("permissions.superusers")
bot := bot.NewBot(nick, pass, channels, dbFilename, superusers)
if err := bot.Start(); err != nil {
logrus.Fatal(err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
fmt.Print("\r\r\b")
if err := bot.Stop(); err != nil {
logrus.Fatal(err)
}
}
示例2: ReadDir
func ReadDir(path string) []os.FileInfo {
wd := ""
p := ""
if viper.GetString("WorkingDir") != "" {
wd = viper.GetString("WorkingDir")
}
if strings.Contains(path, "..") {
jww.ERROR.Printf("Path %s contains parent directory marker", path)
return nil
}
if filepath.IsAbs(path) {
jww.ERROR.Printf("Path %s is an absolute path", path)
return nil
}
p = filepath.Clean(path)
p = filepath.Join(wd, p)
list, err := ioutil.ReadDir(p)
if err != nil {
jww.ERROR.Printf("Failed to read Directory %s with error message %s", path, err)
return nil
}
return list
}
示例3: build
func build(watches ...bool) error {
// Hugo writes the output to memory instead of the disk
// This is only used for benchmark testing. Cause the content is only visible
// in memory
if renderToMemory {
hugofs.DestinationFS = new(afero.MemMapFs)
// Rendering to memoryFS, publish to Root regardless of publishDir.
viper.Set("PublishDir", "/")
}
if err := copyStatic(); err != nil {
return fmt.Errorf("Error copying static files to %s: %s", helpers.AbsPathify(viper.GetString("PublishDir")), err)
}
watch := false
if len(watches) > 0 && watches[0] {
watch = true
}
if err := buildSite(buildWatch || watch); err != nil {
return fmt.Errorf("Error building site: %s", err)
}
if buildWatch {
jww.FEEDBACK.Println("Watching for changes in", helpers.AbsPathify(viper.GetString("ContentDir")))
jww.FEEDBACK.Println("Press Ctrl+C to stop")
utils.CheckErr(NewWatcher(0))
}
return nil
}
示例4: copyStatic
func copyStatic() error {
staticDir := helpers.AbsPathify(viper.GetString("StaticDir")) + "/"
if _, err := os.Stat(staticDir); os.IsNotExist(err) {
jww.ERROR.Println("Unable to find Static Directory:", staticDir)
return nil
}
publishDir := helpers.AbsPathify(viper.GetString("PublishDir")) + "/"
syncer := fsync.NewSyncer()
syncer.NoTimes = viper.GetBool("notimes")
syncer.SrcFs = hugofs.SourceFs
syncer.DestFs = hugofs.DestinationFS
themeDir, err := helpers.GetThemeStaticDirPath()
if err != nil {
jww.ERROR.Println(err)
return nil
}
if themeDir != "" {
// Copy Static to Destination
jww.INFO.Println("syncing from", themeDir, "to", publishDir)
utils.CheckErr(syncer.Sync(publishDir, themeDir), fmt.Sprintf("Error copying static files of theme to %s", publishDir))
}
// Copy Static to Destination
jww.INFO.Println("syncing from", staticDir, "to", publishDir)
return syncer.Sync(publishDir, staticDir)
}
示例5: loadConfig
func loadConfig(filenamePath *string, filename *string) {
log := logging.MustGetLogger("log")
viper.SetConfigName(*filename)
viper.AddConfigPath(*filenamePath)
if err := viper.ReadInConfig(); err != nil {
log.Critical("Unable to load config file:", err)
os.Exit(1)
}
switch viper.GetString("logtype") {
case "critical":
logging.SetLevel(0, "")
case "error":
logging.SetLevel(1, "")
case "warning":
logging.SetLevel(2, "")
case "notice":
logging.SetLevel(3, "")
case "info":
logging.SetLevel(4, "")
case "debug":
logging.SetLevel(5, "")
log.Debug("\"debug\" is selected")
default:
logging.SetLevel(2, "")
//log.Debug("\"default\" is selected (warning)")
}
log.Debug("loadConfig func:")
log.Debug(" path: %s", *filenamePath)
log.Debug(" filename: %s", *filename)
log.Debug(" logtype in file config is \"%s\"", viper.GetString("logtype"))
}
示例6: main
func main() {
viper.SetConfigName("config")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
urls := viper.GetStringMapString("urls")
username := viper.GetString("auth.username")
password := viper.GetString("auth.password")
for title, url := range urls {
c := Checker{
Title: title,
URL: url,
Username: username,
Password: password,
}
go func() {
for {
if err := c.Check(); err != nil {
log.Println(err)
}
time.Sleep(time.Second * 5)
}
}()
}
select {}
}
示例7: FindArchetype
func FindArchetype(kind string) (outpath string) {
search := []string{helpers.AbsPathify(viper.GetString("archetypeDir"))}
if viper.GetString("theme") != "" {
themeDir := path.Join(helpers.AbsPathify("themes/"+viper.GetString("theme")), "/archetypes/")
if _, err := os.Stat(themeDir); os.IsNotExist(err) {
jww.ERROR.Println("Unable to find archetypes directory for theme :", viper.GetString("theme"), "in", themeDir)
} else {
search = append(search, themeDir)
}
}
for _, x := range search {
// If the new content isn't in a subdirectory, kind == "".
// Therefore it should be excluded otherwise `is a directory`
// error will occur. github.com/spf13/hugo/issues/411
var pathsToCheck []string
if kind == "" {
pathsToCheck = []string{"default.md", "default"}
} else {
pathsToCheck = []string{kind + ".md", kind, "default.md", "default"}
}
for _, p := range pathsToCheck {
curpath := path.Join(x, p)
jww.DEBUG.Println("checking", curpath, "for archetypes")
if exists, _ := helpers.Exists(curpath); exists {
jww.INFO.Println("curpath: " + curpath)
return curpath
}
}
}
return ""
}
示例8: ResetSystemUser
// ResetSystemUser reset password for a system user
func (*UsersController) ResetSystemUser(ctx *gin.Context) {
var systemUserJSON resetSystemUserJSON
ctx.Bind(&systemUserJSON)
if !strings.HasPrefix(systemUserJSON.Username, "tat.system") {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Username does not begin with tat.system (%s), it's not possible to reset password for this user", systemUserJSON.Username))
return
}
var systemUserToReset = models.User{}
err := systemUserToReset.FindByUsername(systemUserJSON.Username)
if err != nil {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s does not exist", systemUserJSON.Username))
return
}
if !systemUserToReset.IsSystem {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s is not a system user", systemUserJSON.Username))
return
}
newPassword, err := systemUserToReset.ResetSystemUserPassword()
if err != nil {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Reset password for %s (system user) failed", systemUserJSON.Username))
return
}
ctx.JSON(http.StatusOK, gin.H{
"message": "Reset password successfull",
"username": systemUserToReset.Username,
"password": newPassword,
"url": fmt.Sprintf("%s://%s:%s%s", viper.GetString("exposed_scheme"), viper.GetString("exposed_host"), viper.GetString("exposed_port"), viper.GetString("exposed_path")),
})
}
示例9: getDbParameter
// getDbParameter gets value of tat parameter
// return values if not "" AND not "false"
// used by db_user, db_password and db_rs_tags
func getDbParameter(key string) string {
value := ""
if viper.GetString(key) != "" && viper.GetString(key) != "false" {
value = viper.GetString(key)
}
return value
}
示例10: Verify
// Verify is called by user, after receive email to validate his account
func (u *UsersController) Verify(ctx *gin.Context) {
var user = &models.User{}
username, err := GetParam(ctx, "username")
if err != nil {
return
}
tokenVerify, err := GetParam(ctx, "tokenVerify")
if err != nil {
return
}
if username != "" && tokenVerify != "" {
isNewUser, password, err := user.Verify(username, tokenVerify)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"info": fmt.Sprintf("Error on verify token for username %s %s", username, err.Error())})
} else {
ctx.JSON(http.StatusOK, gin.H{
"message": "Verification successfull",
"username": username,
"password": password,
"url": fmt.Sprintf("%s://%s:%s%s", viper.GetString("exposed_scheme"), viper.GetString("exposed_host"), viper.GetString("exposed_port"), viper.GetString("exposed_path")),
})
if isNewUser {
go models.WSUser(&models.WSUserJSON{Action: "verify", Username: username})
}
}
} else {
ctx.JSON(http.StatusBadRequest, gin.H{"info": fmt.Sprintf("username %s or token empty", username)})
}
}
示例11: Convert
// Convert a "normal" user to a "system" user
func (*UsersController) Convert(ctx *gin.Context) {
var convertJSON convertUserJSON
ctx.Bind(&convertJSON)
if !strings.HasPrefix(convertJSON.Username, "tat.system") {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Username does not begin with tat.system (%s), it's not possible to convert this user", convertJSON.Username))
return
}
var userToConvert = models.User{}
err := userToConvert.FindByUsername(convertJSON.Username)
if err != nil {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s does not exist", convertJSON.Username))
return
}
if userToConvert.IsSystem {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s is already a system user", convertJSON.Username))
return
}
newPassword, err := userToConvert.ConvertToSystem(utils.GetCtxUsername(ctx), convertJSON.CanWriteNotifications)
if err != nil {
AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Convert %s to system user failed", convertJSON.Username))
return
}
ctx.JSON(http.StatusOK, gin.H{
"message": "Verification successfull",
"username": userToConvert.Username,
"password": newPassword,
"url": fmt.Sprintf("%s://%s:%s%s", viper.GetString("exposed_scheme"), viper.GetString("exposed_host"), viper.GetString("exposed_port"), viper.GetString("exposed_path")),
})
}
示例12: setupLogging
func setupLogging() {
switch viper.GetString("log-level") {
case "debug":
log.SetLevel(log.DebugLevel)
case "info":
log.SetLevel(log.InfoLevel)
case "warn":
log.SetLevel(log.WarnLevel)
case "error":
log.SetLevel(log.ErrorLevel)
case "fatal":
log.SetLevel(log.FatalLevel)
default:
log.WithField("log-level", viper.GetString("log-level")).Warning("invalid log level. defaulting to info.")
log.SetLevel(log.InfoLevel)
}
switch viper.GetString("log-format") {
case "text":
log.SetFormatter(new(log.TextFormatter))
case "json":
log.SetFormatter(new(log.JSONFormatter))
default:
log.WithField("log-format", viper.GetString("log-format")).Warning("invalid log format. defaulting to text.")
log.SetFormatter(new(log.TextFormatter))
}
}
示例13: parseDefaultPygmentsOpts
func parseDefaultPygmentsOpts() (map[string]string, error) {
options := make(map[string]string)
err := parseOptions(options, viper.GetString("PygmentsOptions"))
if err != nil {
return nil, err
}
if viper.IsSet("PygmentsStyle") {
options["style"] = viper.GetString("PygmentsStyle")
}
if viper.IsSet("PygmentsUseClasses") {
if viper.GetBool("PygmentsUseClasses") {
options["noclasses"] = "false"
} else {
options["noclasses"] = "true"
}
}
if _, ok := options["encoding"]; !ok {
options["encoding"] = "utf8"
}
return options, nil
}
示例14: Initdb
func Initdb() *gorm.DB {
log := logging.MustGetLogger("log")
log.Debug("db path: %s", viper.GetString("db.path"))
log.Debug("db filename: %s", viper.GetString("db.filename"))
db, err := gorm.Open(
"sqlite3",
filepath.Join(
viper.GetString("db.path"),
viper.GetString("db.filename"),
),
)
if err != nil {
log.Critical("Unable to open db file: %s", err)
os.Exit(1)
}
if viper.GetString("logtype") == "debug" {
db.LogMode(viper.GetBool("debug"))
}
db.CreateTable(new(Temperature))
db.DB().Ping()
return &db
}
示例15: copyStatic
func copyStatic() error {
publishDir := helpers.AbsPathify(viper.GetString("PublishDir")) + "/"
// If root, remove the second '/'
if publishDir == "//" {
publishDir = "/"
}
syncer := fsync.NewSyncer()
syncer.NoTimes = viper.GetBool("notimes")
syncer.SrcFs = hugofs.SourceFs
syncer.DestFs = hugofs.DestinationFS
themeDir, err := helpers.GetThemeStaticDirPath()
if err != nil {
jww.ERROR.Println(err)
return nil
}
// Copy the theme's static directory
if themeDir != "" {
jww.INFO.Println("syncing from", themeDir, "to", publishDir)
utils.CheckErr(syncer.Sync(publishDir, themeDir), fmt.Sprintf("Error copying static files of theme to %s", publishDir))
}
// Copy the site's own static directory
staticDir := helpers.AbsPathify(viper.GetString("StaticDir")) + "/"
if _, err := os.Stat(staticDir); err == nil {
jww.INFO.Println("syncing from", staticDir, "to", publishDir)
return syncer.Sync(publishDir, staticDir)
} else if os.IsNotExist(err) {
jww.WARN.Println("Unable to find Static Directory:", staticDir)
}
return nil
}