diff --git a/README.md b/README.md index 1d2db44..e0047ba 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,12 @@ See the example in [server.yaml](example/server.yaml) file. ```yaml api_key: - chatgpt: CHATGPT_API_KEY # <- Replace with your API Key - deepl: DEEPL_API_KEY # <- Replace with your API Key + chatgpt: + value: CHATGPT_API_KEY # <- Replace with your API Key + # file: $HOME/secrets/chatgpt.txt # <- You can also specify the file where to read api key + deepl: + value: DEEPL_API_KEY # <- Replace with your API Key + # file: $HOME/secrets/deepl.txt # <- You can also specify the file where to read api key ``` ## DeepLX @@ -41,7 +45,9 @@ See the example in [server.yaml](example/server.yaml) file. ```yaml api_key: - deeplx: DEEPLX_API_KEY # <- Replace with your API Key + deeplx: + value: DEEPLX_API_KEY # <- Replace with your API Key + # file: $HOME/secrets/deeplx.txt # <- You can also specify the file where to read api key host: deeplx: 127.0.0.1:1188 # <- Replace with your server IP address and port ``` diff --git a/config.go b/config.go index ae240b4..24d90d9 100644 --- a/config.go +++ b/config.go @@ -3,6 +3,7 @@ package main import ( "fmt" "os" + "strings" "github.com/eeeXun/gtt/internal/style" "github.com/eeeXun/gtt/internal/translate" @@ -160,8 +161,14 @@ func configInit() { if err := serverConfig.ReadInConfig(); err == nil { // api key for _, name := range []string{"ChatGPT", "DeepL", "DeepLX"} { - if serverConfig.Get(fmt.Sprintf("api_key.%s", name)) != nil { - translators[name].SetAPIKey(serverConfig.GetString(fmt.Sprintf("api_key.%s", name))) + // Read from value first, then read from file + if serverConfig.Get(fmt.Sprintf("api_key.%s.value", name)) != nil { + translators[name].SetAPIKey(serverConfig.GetString(fmt.Sprintf("api_key.%s.value", name))) + } else if serverConfig.Get(fmt.Sprintf("api_key.%s.file", name)) != nil { + buff, err := os.ReadFile(os.ExpandEnv(serverConfig.GetString(fmt.Sprintf("api_key.%s.file", name)))) + if err == nil { + translators[name].SetAPIKey(strings.TrimSpace(string(buff))) + } } } // host diff --git a/example/server.yaml b/example/server.yaml index 733172f..54d54a6 100644 --- a/example/server.yaml +++ b/example/server.yaml @@ -1,7 +1,13 @@ # This file should be located at $XDG_CONFIG_HOME/gtt/server.yaml or $HOME/.config/gtt/server.yaml. api_key: - chatgpt: CHATGPT_API_KEY - deepl: DEEPL_API_KEY - deeplx: DEEPLX_API_KEY + chatgpt: + value: CHATGPT_API_KEY + # file: $HOME/secrets/chatgpt.txt + deepl: + value: DEEPL_API_KEY + # file: $HOME/secrets/deepl.txt + deeplx: + value: DEEPLX_API_KEY + # file: $HOME/secrets/deeplx.txt host: deeplx: 127.0.0.1:1188