Home > OS >  Router condition run
Router condition run

Time:01-07

I have api I want to run this api with different conditions it is like this is my config

    config := api.Config{
        Version:          VERSION,
        Host:             Setting.Host,
        Key:              Setting.Key,
        Https:            Setting.Https,
        Enable:           Setting.Enable,
    }

if in config yaml Enable is true I want to run the router with extra value

    if config.Enable {
        test_f := func() (func(), error) {
            return df, nil
        }
        router := api.MakeRouter(&config, test_f)
    }

when enable is false

    else {
        router := api.MakeRouter(&config, nil)

    }

but my problem is that I have another condition. in here I get an error which is undefined: router

    if config.Https {
        go router.RunTLS(config.Host, config.Key)
    } else {
        go router.Run(config.Host)
    }
```
how can I solve this

CodePudding user response:

You're defining the variable router inside a block, which means it is scoped to that block; it doesn't exist outside that block. You need to define it outside the block, and assign to it inside:

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)
}

Or, alternatively, since only one value is different, deal with that value only in the if block, and create the router outside:

var test_f func() (func(), error)
if config.Enable {
    test_f = func() (func(), error) {
        return df, nil
    }
}
router := api.MakeRouter(&config, test_f)

The latter would be my preference in general because it's more clear what's happening, but if more things are likely to change between the two cases, that might be an argument for the first approach.

Identifier scope is detailed in the spec: https://go.dev/ref/spec#Declarations_and_scope

  •  Tags:  
  • Related