Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

G101: Potential hardcoded credentials (gosec) #438

Open
wwcchh0123 opened this issue Nov 8, 2024 · 0 comments
Open

G101: Potential hardcoded credentials (gosec) #438

wwcchh0123 opened this issue Nov 8, 2024 · 0 comments

Comments

@wwcchh0123
Copy link
Contributor

lint 解释

  • 该 lint 出现是提醒开发者代码中可能存在硬编码的凭证(如用户名、密码、API 密钥等)。而硬编码凭证会导致安全风险,因为这些凭证在源代码中可被轻易访问,可能会被恶意用户利用。为了尽可能减少安全风险,可使用环境变量或者配置文件进行读取

错误用法

func main() {
    // 硬编码的凭证
    username := "admin"
    password := "secret123"

    fmt.Printf("Username: %s, Password: %s\n", username, password)
}

正确用法

  • 通过环境变量
type Config struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

func main() {
    username := os.Getenv("APP_USERNAME")
    password := os.Getenv("APP_PASSWORD")

    if username == "" || password == "" {
        fmt.Println("用户名或密码未设置")
        return
    }

    fmt.Printf("Username: %s, Password: %s\n", username, password)
}
  • 通过配置文件
func main() {
    configFile, err := ioutil.ReadFile("config.json")
    if err != nil {
        fmt.Println("无法读取配置文件:", err)
        return
    }

    var config Config
    if err := json.Unmarshal(configFile, &config); err != nil {
        fmt.Println("无法解析配置文件:", err)
        return
    }

    fmt.Printf("Username: %s, Password: %s\n", config.Username, config.Password)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant