0

I have the following yaml openapi 3 config' for my servers:

servers:
  - url: "localhost"
    description: "localhost development server"
    variables:
        port:
            default: ":10000"

Getting at those values via viper is trivial without that pesky dash, but I'm struggling with it (which is necessary to make the yaml openapi 3 compliant.

Doing this:

servers := viper.Get("servers")
fmt.Println(reflect.TypeOf(servers))
fmt.Println(servers)

Tells me this:

[]interface {}
[map[description:localhost development server url:localhost variables:map[port:map[default::10000]]]]

But my n00bie golang abilities are lacking the ninja skillz to retrieve that :10000 value for port.

Any help much appreciated!

glowkeeper
  • 209
  • 2
  • 11
  • 1
    Unrelated to the question - it should be `url: "localhost{port}"`, i.e. the variable needs to be actually included in the `url`. – Helen Jun 25 '20 at 12:51
  • @Helen - ah yes, I think I removed that yesterday, as I was having enough problems getting at the values without that added complication! If I can get everything above working, I'll add it back, pronto :) – glowkeeper Jun 25 '20 at 13:00
  • Just an fyi - I have (currently) given up trying to support `openapi 3` and have removed dashes from the `yaml`. It means I've had to introduce nasty hacks regarding multiple parameters, but hey, I have something that works for the proof of concept I'm working on. In other words, I'll revisit this later ;) – glowkeeper Jul 07 '20 at 10:18

1 Answers1

0

servers is an array. Assuming Viper cannot deal with arrays, you first have to index servers to get the object in it:

server:=servers[0]

Once you have the server, assuming it is a map[string]interface{}, you can descend down:

if v, ok:=server["variables"]; ok {
   if varMap, ok:=v.(map[string]interface{}); ok {
      if p, ok:=varMap["port"]; ok {
        if port, ok:=p.(map[string]interface{}); ok {
           if d, ok:=port["default"]; ok {
               defaultValue=fmt.Sprint(d)
           } 
        }
      }
   }
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • I've tried something like that already, but it falls down at the first hurdle: `server:=servers[0]`, giving the error `Invalid operation: servers[0] (type interface {} does not support indexing)` – glowkeeper Jun 25 '20 at 16:12