fix: Clear error message when provided config is not a text file (#11787)
This commit is contained in:
parent
614aec6d3f
commit
b5f7ca4e08
|
|
@ -581,7 +581,17 @@ func LoadConfigFile(config string) ([]byte, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// If it isn't a https scheme, try it as a file
|
// If it isn't a https scheme, try it as a file
|
||||||
return os.ReadFile(config)
|
buffer, err := os.ReadFile(config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
mimeType := http.DetectContentType(buffer)
|
||||||
|
if !strings.Contains(mimeType, "text/plain") {
|
||||||
|
return nil, fmt.Errorf("provided config is not a TOML file: %s", config)
|
||||||
|
}
|
||||||
|
|
||||||
|
return buffer, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func fetchConfig(u *url.URL) ([]byte, error) {
|
func fetchConfig(u *url.URL) ([]byte, error) {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,13 @@
|
||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
@ -26,6 +29,32 @@ import (
|
||||||
"github.com/influxdata/telegraf/plugins/parsers/json"
|
"github.com/influxdata/telegraf/plugins/parsers/json"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestReadBinaryFile(t *testing.T) {
|
||||||
|
// Create a temporary binary file using the Telegraf tool custom_builder to pass as a config
|
||||||
|
wd, err := os.Getwd()
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
err := os.Chdir(wd)
|
||||||
|
require.NoError(t, err)
|
||||||
|
})
|
||||||
|
|
||||||
|
err = os.Chdir("../")
|
||||||
|
require.NoError(t, err)
|
||||||
|
tmpdir := t.TempDir()
|
||||||
|
binaryFile := filepath.Join(tmpdir, "custom_builder")
|
||||||
|
cmd := exec.Command("go", "build", "-o", binaryFile, "./tools/custom_builder")
|
||||||
|
var outb, errb bytes.Buffer
|
||||||
|
cmd.Stdout = &outb
|
||||||
|
cmd.Stderr = &errb
|
||||||
|
err = cmd.Run()
|
||||||
|
|
||||||
|
require.NoError(t, err, fmt.Sprintf("stdout: %s, stderr: %s", outb.String(), errb.String()))
|
||||||
|
c := NewConfig()
|
||||||
|
err = c.LoadConfig(binaryFile)
|
||||||
|
require.Error(t, err)
|
||||||
|
require.ErrorContains(t, err, "provided config is not a TOML file")
|
||||||
|
}
|
||||||
|
|
||||||
func TestConfig_LoadSingleInputWithEnvVars(t *testing.T) {
|
func TestConfig_LoadSingleInputWithEnvVars(t *testing.T) {
|
||||||
c := NewConfig()
|
c := NewConfig()
|
||||||
require.NoError(t, os.Setenv("MY_TEST_SERVER", "192.168.1.1"))
|
require.NoError(t, os.Setenv("MY_TEST_SERVER", "192.168.1.1"))
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue