duanmi8349 2018-06-21 17:03
浏览 54
已采纳

ReadLine和验证

In one file that's in path /operations/validate:

package operations

import (
   "strings"
)

func CheckEnv(environment string) bool {
   env := strings.ToLower(environment)
   return env == "qa" || env == "dev" || env == "prd"
}

In the next file that calls the function:

package prompts

import (
    "bufio"
    "fmt"
    "os"
    val "thirsty/operations"
)

// AskEnv prompts for Environment
func AskEnv() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter environment (ex: dev, qa, prd): ")
    environment, _ := reader.ReadString('
')
    fmt.Println(environment)
    env := val.CheckEnv(environment)
    if !env {
        fmt.Printf("Invalid Argument: No environment found for %s", environment)
        return
    }

    os.Setenv("env", environment)
    fmt.Printf("Environment set to %s", environment)
}

During the prompt, I've tried qa or dev but I keep getting false as response. I am not sure why this is occurring and would appreciate any insight provided.

  • 写回答

1条回答 默认 最新

  • douqian1835 2018-06-21 19:39
    关注

    bufio.Reader.ReadString includes the delimiter in the returned string, so your CheckEnv function ends up doing (for example):

    return "qa
    " == "qa" || "qa
    " == "dev" || "qa
    " == "prd"
    

    which is of course never going to return true.

    You can solve this by using one of the strings.Trim*, like TrimSpace, to remove the trailing line ending character(s) and other unwanted whitespace, like this:

    func CheckEnv(environment string) bool {
       env := strings.ToLower(strings.TrimSpace(environment))
       return env == "qa" || env == "dev" || env == "prd"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记