Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(lite): load dotenv files before server startup (#3618)

tsumona731395b1036
diff --git a/cmd/server/main.go b/cmd/server/main.go
index ff509a4f7..fd27d167d 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -35,12 +35,25 @@ import (
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/container"
+ "github.com/Tencent/WeKnora/internal/envfile"
+ "github.com/Tencent/WeKnora/internal/handler"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/runtime"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
func main() {
+ // Load dotenv configuration before any container provider reads it.
+ // Explicit ENV_FILE is honored on every build; automatic .env.lite
+ // discovery is scoped to Lite builds (internal/handler.Edition is
+ // injected at build time), so a standard binary built in the repo root
+ // never picks up Lite defaults. Process variables remain authoritative.
+ if err := envfile.Load(handler.Edition == "lite"); err != nil {
+ fmt.Fprintf(os.Stderr, "warning: %v\n", err)
+ }
+ // Dotenv loading happens after the logger package initialized, so
+ // re-apply file-based LOG_LEVEL / LOG_PATH (mirrors cmd/desktop).
+ logger.ConfigureFromEnv()
// Set Gin mode
if os.Getenv("GIN_MODE") == "release" {
gin.SetMode(gin.ReleaseMode)
diff --git a/docs/LITE.md b/docs/LITE.md
index e3cadc293..cb109f1e7 100644
--- a/docs/LITE.md
+++ b/docs/LITE.md
@@ -13,4 +13,14 @@ Lite 面向希望快速在本地使用、部署尽量简单的场景;标准版
| **网络暴露** | **默认仅本机访问**;可按需配置,**选择是否放行到公网** | 按部署与安全策略自行绑定地址与网关 |
-若你不需要多团队协作、复杂解析流水线与多服务架构,Lite 更适合个人或小团队在本机零依赖试用;需要共享空间、多空间与完整解析引擎矩阵时,请使用标准版。
\ No newline at end of file
+若你不需要多团队协作、复杂解析流水线与多服务架构,Lite 更适合个人或小团队在本机零依赖试用;需要共享空间、多空间与完整解析引擎矩阵时,请使用标准版。
+
+## 配置文件
+
+直接运行 `WeKnora-lite` 时,程序会自动读取 `.env.lite`——先找程序所在目录(发行包解压后的目录结构),再找当前目录,无需手动 `source`。复制发行包里的 `.env.lite.example` 为 `.env.lite` 即可开始配置。注意:
+
+- 只有 Lite 构建的二进制会做这件事;标准版二进制不会自动读取任何 dotenv 文件。
+- 不再用 `.env` 做补充:`.env.lite` 是 Lite 唯一的文件配置来源,避免标准版模板里的 `REDIS_ADDR`、Langfuse 凭据等变量意外切走 Lite 的内存队列或打开链路追踪。
+- 如需指定其他文件,可设置 `ENV_FILE` 环境变量(标准版同样生效)。
+- 命令行或服务管理器中已经设置的环境变量优先于配置文件。
+- 写在 `.env.lite` 里的 `LOG_LEVEL` / `LOG_PATH` 会生效(加载后会重新应用日志配置)。
diff --git a/internal/envfile/envfile.go b/internal/envfile/envfile.go
new file mode 100644
index 000000000..4ec509b36
--- /dev/null
+++ b/internal/envfile/envfile.go
@@ -0,0 +1,61 @@
+// Package envfile loads optional dotenv configuration before the application
+// container reads environment variables.
+package envfile
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/joho/godotenv"
+)
+
+// Load reads ENV_FILE when it is set, on any build. Otherwise it only acts on
+// Lite builds, loading .env.lite — first beside the running executable (the
+// tarball layout), then the current working directory (the repo/dev layout).
+// There is deliberately no .env fallback: a standard binary built in the repo
+// root must never pick up Lite defaults, and on Lite builds .env.lite is the
+// single source of file defaults, so a stray .env cannot flip Lite into the
+// Redis/Asynq path or enable Langfuse tracing.
+//
+// godotenv never overwrites a variable already present in the process
+// environment, so deployment-level settings always win over files.
+//
+// Missing default files are normal and ignored. An explicitly requested file,
+// or a present file with invalid syntax, is reported to the caller.
+func Load(lite bool) error {
+ if path := strings.TrimSpace(os.Getenv("ENV_FILE")); path != "" {
+ if err := godotenv.Load(path); err != nil {
+ return fmt.Errorf("load ENV_FILE %q: %w", path, err)
+ }
+ return nil
+ }
+ if !lite {
+ return nil
+ }
+
+ for _, path := range liteDotenvPaths() {
+ if err := godotenv.Load(path); err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ return fmt.Errorf("load %s: %w", path, err)
+ }
+ return nil
+ }
+ return nil
+}
+
+// liteDotenvPaths returns the .env.lite candidate locations in priority
+// order: beside the running executable first, then the working directory.
+func liteDotenvPaths() []string {
+ paths := []string{".env.lite"}
+ if exe, err := os.Executable(); err == nil {
+ if dir := filepath.Dir(exe); dir != "" && dir != "." {
+ paths = append([]string{filepath.Join(dir, ".env.lite")}, paths...)
+ }
+ }
+ return paths
+}
diff --git a/internal/envfile/envfile_test.go b/internal/envfile/envfile_test.go
new file mode 100644
index 000000000..70a820797
--- /dev/null
+++ b/internal/envfile/envfile_test.go
@@ -0,0 +1,102 @@
+package envfile
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestLoadLiteBuildLoadsEnvLite(t *testing.T) {
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(
+ filepath.Join(dir, ".env.lite"),
+ []byte("DB_DRIVER=sqlite\nJWT_SECRET=from-lite\n"),
+ 0o600,
+ ))
+ t.Chdir(dir)
+
+ unsetEnvForTest(t, "ENV_FILE", "DB_DRIVER", "JWT_SECRET")
+ t.Setenv("JWT_SECRET", "from-process")
+
+ require.NoError(t, Load(true))
+ assert.Equal(t, "sqlite", os.Getenv("DB_DRIVER"))
+ assert.Equal(t, "from-process", os.Getenv("JWT_SECRET"), "process environment must take precedence")
+}
+
+func TestLoadLiteBuildIgnoresDotEnv(t *testing.T) {
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, ".env.lite"), []byte("DB_DRIVER=sqlite\n"), 0o600))
+ require.NoError(t, os.WriteFile(
+ filepath.Join(dir, ".env"),
+ []byte("DB_DRIVER=postgres\nREDIS_ADDR=redis:6379\n"),
+ 0o600,
+ ))
+ t.Chdir(dir)
+
+ unsetEnvForTest(t, "ENV_FILE", "DB_DRIVER", "REDIS_ADDR")
+
+ require.NoError(t, Load(true))
+ assert.Equal(t, "sqlite", os.Getenv("DB_DRIVER"), ".env.lite wins; .env must not override it")
+ assert.Empty(t, os.Getenv("REDIS_ADDR"), ".env must not be consulted on Lite builds")
+}
+
+func TestLoadStandardBuildLoadsNothing(t *testing.T) {
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, ".env.lite"), []byte("DB_DRIVER=sqlite\n"), 0o600))
+ require.NoError(t, os.WriteFile(filepath.Join(dir, ".env"), []byte("DB_DRIVER=postgres\n"), 0o600))
+ t.Chdir(dir)
+
+ unsetEnvForTest(t, "ENV_FILE", "DB_DRIVER")
+
+ require.NoError(t, Load(false))
+ assert.Empty(t, os.Getenv("DB_DRIVER"), "standard builds must not auto-load dotenv files")
+}
+
+func TestLoadExplicitEnvFileOnStandardBuild(t *testing.T) {
+ dir := t.TempDir()
+ custom := filepath.Join(dir, "custom.env")
+ require.NoError(t, os.WriteFile(custom, []byte("DB_DRIVER=custom\n"), 0o600))
+ t.Chdir(dir)
+
+ unsetEnvForTest(t, "DB_DRIVER")
+ t.Setenv("ENV_FILE", custom)
+
+ require.NoError(t, Load(false))
+ assert.Equal(t, "custom", os.Getenv("DB_DRIVER"), "explicit ENV_FILE is honored on every build")
+}
+
+func TestLoadMissingFilesAreIgnored(t *testing.T) {
+ t.Chdir(t.TempDir())
+ unsetEnvForTest(t, "ENV_FILE")
+ require.NoError(t, Load(true))
+}
+
+func TestLoadInvalidSyntaxIsReported(t *testing.T) {
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, ".env.lite"), []byte("DB_DRIVER=\"unterminated\n"), 0o600))
+ t.Chdir(dir)
+
+ unsetEnvForTest(t, "ENV_FILE", "DB_DRIVER")
+
+ err := Load(true)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), ".env.lite")
+}
+
+func unsetEnvForTest(t *testing.T, keys ...string) {
+ t.Helper()
+ for _, key := range keys {
+ value, exists := os.LookupEnv(key)
+ require.NoError(t, os.Unsetenv(key))
+ t.Cleanup(func() {
+ if exists {
+ _ = os.Setenv(key, value)
+ } else {
+ _ = os.Unsetenv(key)
+ }
+ })
+ }
+}