func CreateCloudCredential()

in cloudsso/refresh.go [102:172]


func CreateCloudCredential(prefix string, accessToken string, options CloudCredentialOptions, client *http.Client) (*CloudCredentialResponse, error) {
	urlFetch := fmt.Sprintf("%s/cloud-credentials", prefix)

	// Prepare request body
	data, err := json.Marshal(options)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal options: %w", err)
	}

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

	// Set headers
	req.Header.Set("accept", "application/json")
	req.Header.Set("content-type", "application/json")
	req.Header.Set("authorization", fmt.Sprintf("Bearer %s", accessToken))
	req.Header.Set("user-agent", "aliyun/CLI-"+cli.Version)

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

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

	// Handle HTTP errors
	if resp.StatusCode >= 400 && resp.StatusCode < 500 {
		bodyBytes, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, fmt.Errorf("failed to read error response body: %w", err)
		}
		bodyString := string(bodyBytes)
		var errResp map[string]interface{}
		if err := json.Unmarshal(bodyBytes, &errResp); err != nil {
			// 如果解析 JSON 失败,返回原始响应体作为错误信息
			return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, bodyString)
		}
		return nil, fmt.Errorf("HTTP %d: %s: %s %s", resp.StatusCode, bodyString, errResp["ErrorCode"], errResp["ErrorMessage"])
	}

	// Parse successful response
	var result CloudCredentialResponseRaw
	if err := json.Unmarshal(body, &result); err != nil {
		return nil, fmt.Errorf("failed to parse response: %w", err)
	}

	if result.CloudCredential.Expiration != "" {
		// Parse expiration time
		expiration, err := time.Parse(time.RFC3339, result.CloudCredential.Expiration)
		if err != nil {
			return nil, fmt.Errorf("failed to parse expiration time: %w", err)
		}
		result.CloudCredential.ExpirationInt64 = expiration.Unix()
	}

	return result.CloudCredential, nil
}