func sendPostRequest()

in action/k8s/utils/http.go [105:178]


func sendPostRequest(context *ContextInfo, createCrdPath string, filePath string) (string, error) {
	certFile := context.ClientCert
	keyFile := context.ClientKey
	caCertFile := context.CACert
	url := context.APIServer + createCrdPath
	contentType := context.ContentType

	// Load client certificate and key
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return "", fmt.Errorf("failed to load certificate and key: %v", err)
	}

	// Read CA certificate
	caCert, err := ioutil.ReadFile(caCertFile)
	if err != nil {
		return "", fmt.Errorf("failed to read CA certificate: %v", err)
	}
	caCertPool := x509.NewCertPool()
	if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
		return "", fmt.Errorf("failed to append CA certificate")
	}

	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      caCertPool,
	}
	transport := &http.Transport{TLSClientConfig: tlsConfig}
	client := &http.Client{Transport: transport}

	// Read data from file
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return "", fmt.Errorf("failed to read data file: %v", err)
	}

	// Create a POST request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		return "", fmt.Errorf("failed to create request: %v", err)
	}

	// Set content type
	req.Header.Set("Content-Type", string(contentType))

	// Send the request
	resp, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("failed to send request: %v", err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			tool.Logger.Error("failed to close response body: %v", err)
		}
	}(resp.Body)

	// Read response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("failed to read response: %v", err)
	}

	// Return appropriate response based on status code
	if resp.StatusCode == http.StatusCreated {
		tool.Logger.Infof("Create seata crd success")
		return "", nil
	}
	if resp.StatusCode == http.StatusConflict {
		return "", fmt.Errorf("seata crd already exists")
	} else {
		return "error: " + string(body), err
	}
}