This code is functioning but I don't understand how.
In the code below hostProxy[host] may or may not contain a function. I don't understand how the variable "ok" is defined or how it gets its value. It is not defined before this line.
if fn, ok := hostProxy[host]; ok {
fn.ServeHTTP(w, r)
return
}
if target, ok := hostTarget[host]; ok {
....
}
This is covered in Spec: Index expressions:
An index expression on a map a of type
map[K]V
used in an assignment or initialization of the special formv, ok = a[x] v, ok := a[x] var v, ok = a[x] var v, ok T = a[x]
yields an additional untyped boolean value. The value of
ok
istrue
if the keyx
is present in the map, andfalse
otherwise.
So for example this code:
if fn, ok := hostProxy[host]; ok {
fn.ServeHTTP(w, r)
return
}
Means to get the value associated with host
key from the hostProxy
map, create and store the value in the fn
variable, and the result (whether the key was found in the map) in the ok
variable. And this ok
variable (which will be of type bool
) is used as the condition of the if
statement. So if the host
key is in the hostProxy
map, it goes ahead and uses it.
Yes ok
isn't defined before, but in your example you have :=
which will define variables for you under the hood and will assign values obtained from map lookup
.