github.com/verrazzano/verrazzano@v1.7.1/pkg/httputil/httputil.go (about) 1 // Copyright (c) 2021, 2023, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 package httputil 5 6 import ( 7 "crypto/tls" 8 "crypto/x509" 9 "errors" 10 "fmt" 11 "net/http" 12 13 "github.com/Jeffail/gabs/v2" 14 ) 15 16 // Helper function to extract field from json response body or returns an error containing input error message 17 func ExtractFieldFromResponseBodyOrReturnError(responseBody string, field string, errMsg ...string) (string, error) { 18 jsonString, err := gabs.ParseJSON([]byte(responseBody)) 19 if err != nil { 20 return "", err 21 } 22 23 if token, ok := jsonString.Path(field).Data().(string); ok { 24 return token, nil 25 } 26 27 if toString := jsonString.Path(field).String(); toString != "null" { 28 return toString, nil 29 } 30 31 errorString := "unable to find token in response" 32 if errMsg != nil { 33 errorString = errMsg[0] 34 } 35 return "", errors.New(errorString) 36 37 } 38 39 // Helper function to validate response code for http response 40 func ValidateResponseCode(response *http.Response, validResponseCodes ...int) error { 41 if response != nil && !integerSliceContains(validResponseCodes, response.StatusCode) { 42 statusCodeMsg := `one of response codes ` + fmt.Sprintf("%v", validResponseCodes) 43 if len(validResponseCodes) == 1 { 44 statusCodeMsg = `response code ` + fmt.Sprintf("%v", validResponseCodes[0]) 45 } 46 return fmt.Errorf("expected %s from %s but got %d: %v", statusCodeMsg, response.Request.Method, response.StatusCode, response) 47 } 48 49 return nil 50 } 51 52 func integerSliceContains(slice []int, i int) bool { 53 for _, item := range slice { 54 if item == i { 55 return true 56 } 57 } 58 return false 59 } 60 61 func GetHTTPClientWithRootCA(ca *x509.CertPool) *http.Client { 62 tr := &http.Transport{ 63 TLSClientConfig: &tls.Config{ 64 RootCAs: ca, 65 MinVersion: tls.VersionTLS12}, 66 Proxy: http.ProxyFromEnvironment, 67 } 68 69 // disable the custom DNS resolver 70 // setupCustomDNSResolver(tr, kubeconfigPath) 71 72 return &http.Client{Transport: tr} 73 }