我有 api 我想在不同的條件下運行這個 api 就像這是我的配置
config := api.Config{
Version: VERSION,
Host: Setting.Host,
Key: Setting.Key,
Https: Setting.Https,
Enable: Setting.Enable,
}
如果在配置 yaml Enable 為真,我想用額外的值運行路由器
if config.Enable {
test_f := func() (func(), error) {
return df, nil
}
router := api.MakeRouter(&config, test_f)
}
當啟用為假時
else {
router := api.MakeRouter(&config, nil)
}
但我的問題是我有另一個條件。在這里我得到一個錯誤是undefined: router
if config.Https {
go router.RunTLS(config.Host, config.Key)
} else {
go router.Run(config.Host)
}
```
how can I solve this
uj5u.com熱心網友回復:
您在router塊內定義變數,這意味著它的作用域是該塊;它不存在于該塊之外。您需要在塊外部定義它,并在內部分配給它:
var router api.WhateverTypeRouterIs
if config.Enable {
test_f := func() (func(), error) {
return df, nil
}
router = api.MakeRouter(&config, test_f)
} else {
router = api.MakeRouter(&config, nil)
}
或者,由于只有一個值不同,因此僅在if塊中處理該值,并在外部創建路由器:
var test_f func() (func(), error)
if config.Enable {
test_f = func() (func(), error) {
return df, nil
}
}
router := api.MakeRouter(&config, test_f)
后者通常是我的偏好,因為它更清楚發生了什么,但如果兩種情況之間可能發生更多變化,那可能是第一種方法的論據。
識別符號范圍在規范中有詳細說明:https : //go.dev/ref/spec#Declarations_and_scope
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404481.html
標籤:
上一篇:如何從變數宣告常量?
