Difference between revisions of "Golang Maps"
Jump to navigation
Jump to search
Line 41: | Line 41: | ||
# Nested Structs | # Nested Structs | ||
https://stackoverflow.com/questions/24809235/how-to-initialize-a-nested-struct | https://stackoverflow.com/questions/24809235/how-to-initialize-a-nested-struct | ||
+ | ``` | ||
+ | type Configuration struct { | ||
+ | Val string | ||
+ | Proxy Proxy | ||
+ | } | ||
+ | |||
+ | type Proxy struct { | ||
+ | Address string | ||
+ | Port string | ||
+ | } | ||
+ | |||
+ | func main() { | ||
+ | |||
+ | c := &Configuration{ | ||
+ | Val: "test", | ||
+ | Proxy: Proxy{ | ||
+ | Address: "addr", | ||
+ | Port: "port", | ||
+ | }, | ||
+ | } | ||
+ | fmt.Println(c) | ||
+ | fmt.Println(c.Proxy.Address) | ||
+ | } | ||
+ | The less proper and ugly way but still works: | ||
+ | |||
+ | c := &Configuration{ | ||
+ | Val: "test", | ||
+ | Proxy: struct { | ||
+ | Address string | ||
+ | Port string | ||
+ | }{ | ||
+ | Address: "addr", | ||
+ | Port: "80", | ||
+ | }, | ||
+ | } | ||
+ | ``` |
Revision as of 01:04, 4 August 2021
package main import ( // "string" "fmt" "github.com/go-resty/resty/v2" "encoding/json" "reflect" ) var PDAuthToken = "" var url = "https://api.pagerduty.com/services/XXXXXXX" func test1() { client := resty.New() rsp,err := client.R().SetHeader("Accept", "application/json").SetHeader("Authorization", "Token token="+PDAuthToken).Get(url) if err != nil { fmt.Println(err) return } rspBody := rsp.Body() rspJSON := string(rspBody) // Declared an empty map interface var result map[string]interface{} // Unmarshal or Decode the JSON to the interface. json.Unmarshal([]byte(rspJSON), &result) fmt.Println("Type:", reflect.TypeOf(result)) fmt.Println("Service :", result["service"]) service, valid := result["service"].(map[string]interface{}) fmt.Println("service_alert_grouping_timeout :", service["alert_grouping_timeout"]) _ = valid } func main(){ test1() }
Nested Structs
https://stackoverflow.com/questions/24809235/how-to-initialize-a-nested-struct
type Configuration struct { Val string Proxy Proxy } type Proxy struct { Address string Port string } func main() { c := &Configuration{ Val: "test", Proxy: Proxy{ Address: "addr", Port: "port", }, } fmt.Println(c) fmt.Println(c.Proxy.Address) } The less proper and ugly way but still works: c := &Configuration{ Val: "test", Proxy: struct { Address string Port string }{ Address: "addr", Port: "80", }, }