|
| 1 | +package host |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "crypto/tls" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io/ioutil" |
| 9 | + "log" |
| 10 | + "net/http" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +func MakeRequest(method, url string, body []byte) []byte { |
| 15 | + tr := &http.Transport{ |
| 16 | + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, |
| 17 | + } |
| 18 | + client := &http.Client{Transport: tr} |
| 19 | + |
| 20 | + req, err := http.NewRequest(method, url, bytes.NewBuffer(body)) |
| 21 | + if err != nil { |
| 22 | + log.Fatal(err) |
| 23 | + } |
| 24 | + authParts := strings.SplitN(CurrentHost.UsernamePassword, ":", 2) |
| 25 | + req.SetBasicAuth(authParts[0], authParts[1]) |
| 26 | + req.Header.Set("Content-Type", "application/json") |
| 27 | + req.Header.Set("Accept", "application/json") |
| 28 | + |
| 29 | + resp, err := client.Do(req) |
| 30 | + if err != nil { |
| 31 | + log.Fatal(err) |
| 32 | + } |
| 33 | + defer resp.Body.Close() |
| 34 | + |
| 35 | + respBody, err := ioutil.ReadAll(resp.Body) |
| 36 | + if err != nil { |
| 37 | + log.Fatal(err) |
| 38 | + } |
| 39 | + |
| 40 | + if resp.StatusCode >= 200 && resp.StatusCode < 300 { |
| 41 | + var success struct { |
| 42 | + Message string `json:"message"` |
| 43 | + } |
| 44 | + if err := json.Unmarshal(respBody, &success); err == nil { |
| 45 | + if verbose { |
| 46 | + fmt.Println("Success:", success.Message) |
| 47 | + } |
| 48 | + } else { |
| 49 | + if verbose { |
| 50 | + fmt.Println("Success:", string(respBody)) |
| 51 | + } |
| 52 | + } |
| 53 | + } else { |
| 54 | + var errorResp struct { |
| 55 | + Error struct { |
| 56 | + Code string `json:"code"` |
| 57 | + Message string `json:"message"` |
| 58 | + MessageExtended []struct { |
| 59 | + MessageId string `json:"MessageId"` |
| 60 | + Severity string `json:"Severity"` |
| 61 | + Resolution string `json:"Resolution"` |
| 62 | + Message string `json:"Message"` |
| 63 | + MessageArgs []string `json:"MessageArgs"` |
| 64 | + RelatedProperties []string `json:"RelatedProperties"` |
| 65 | + } `json:"@Message.ExtendedInfo"` |
| 66 | + } `json:"error"` |
| 67 | + } |
| 68 | + if err := json.Unmarshal(respBody, &errorResp); err == nil { |
| 69 | + fmt.Printf("Error: %s - %s\n", errorResp.Error.Code, errorResp.Error.Message) |
| 70 | + for _, info := range errorResp.Error.MessageExtended { |
| 71 | + fmt.Printf(" %s: %s\n", info.Severity, info.Message) |
| 72 | + if info.Resolution != "" { |
| 73 | + fmt.Printf(" Resolution: %s\n", info.Resolution) |
| 74 | + } |
| 75 | + } |
| 76 | + } else { |
| 77 | + fmt.Printf("Error: %s\n", resp.Status) |
| 78 | + fmt.Println(string(respBody)) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + return respBody |
| 83 | +} |
0 commit comments