feat: 添加 InitialAuthToken 方法以优先使用 AgentToken,更新主函数以使用新方法

This commit is contained in:
ryan
2026-03-10 23:34:04 +08:00
parent 096aa17157
commit f3f4980b7d
3 changed files with 54 additions and 1 deletions
+1 -1
View File
@@ -39,7 +39,7 @@ func main() {
)
log.Printf("agent config loaded: server=%s node=%s ip=%s heartbeat_interval=%s sync_interval=%s route_config=%s cert_dir=%s", cfg.ServerURL, cfg.NodeName, cfg.NodeIP, cfg.HeartbeatInterval, cfg.SyncInterval, cfg.RouteConfigPath, cfg.CertDir)
client := httpclient.New(cfg.ServerURL, cfg.AgentToken, cfg.RequestTimeout.Duration())
client := httpclient.New(cfg.ServerURL, cfg.InitialAuthToken(), cfg.RequestTimeout.Duration())
stateStore := state.NewStore(cfg.StatePath)
runner := &agent.Runner{
Config: cfg,
+10
View File
@@ -157,6 +157,16 @@ func validate(cfg *Config) error {
return nil
}
func (cfg *Config) InitialAuthToken() string {
if cfg == nil {
return ""
}
if token := strings.TrimSpace(cfg.AgentToken); token != "" {
return token
}
return strings.TrimSpace(cfg.DiscoveryToken)
}
func (cfg *Config) Save() error {
if cfg == nil {
return errors.New("config 不能为空")
+43
View File
@@ -197,3 +197,46 @@ func TestSavePersistsMillisecondsAndOmitsRuntimeVersions(t *testing.T) {
t.Fatalf("unexpected request timeout: %#v", decoded["request_timeout"])
}
}
func TestInitialAuthToken(t *testing.T) {
tests := []struct {
name string
agentToken string
discoveryToken string
expected string
}{
{
name: "prefer agent token",
agentToken: "agent-token",
discoveryToken: "discovery-token",
expected: "agent-token",
},
{
name: "fallback to discovery token",
agentToken: " ",
discoveryToken: "discovery-token",
expected: "discovery-token",
},
{
name: "nil config returns empty string",
agentToken: "",
discoveryToken: "",
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var cfg *Config
if tt.name != "nil config returns empty string" {
cfg = &Config{
AgentToken: tt.agentToken,
DiscoveryToken: tt.discoveryToken,
}
}
if token := cfg.InitialAuthToken(); token != tt.expected {
t.Fatalf("unexpected initial auth token: %q", token)
}
})
}
}