Go SDK guide

更新时间:
复制 MD 格式

Set up the Go SDK and install the dependency package

go get github.com/alibabacloud-go/docmind-api-20220711@master

If you use Go modules, add the dependency to your go.mod file:

module test

go 1.15

require (
	github.com/alibabacloud-go/darabonba-openapi v0.2.0
	github.com/alibabacloud-go/docmind-api-20220711 v1.4.13
	github.com/alibabacloud-go/tea-utils/v2 v2.0.0
)

Configure authentication

  1. Create an AccessKey.

    For more information, see Create an AccessKey.

    Important

    An AccessKey for an Alibaba Cloud account can access all APIs. For enhanced security, we recommend using a RAM user for API calls. To do this, grant the RAM user the required permissions for Document Intelligence and use the RAM user's AccessKey to call the SDK. For more information, see Control access to Document Intelligence by using a RAM user.

    We strongly recommend not hardcoding your AccessKey ID and AccessKey secret in your code. This can lead to AccessKey leaks and compromise the security of your account's resources.

    If leaking a RAM user's AccessKey is a concern, you can create a RAM role and use temporary credentials from STS to call the service. For more information, see Call a service by using a temporary account authorized by STS.

  2. Add the Alibaba Cloud credentials dependency.

    go get -u github.com/aliyun/credentials-go
  3. Configure authentication.

    This topic uses a configuration file as an example. For detailed instructions, see Configuration Methods.

Submit a document processing job

Document Intelligence provides an asynchronous job API. You can call this API with the Go SDK by uploading a local file or providing a file URL.

For large files that may require longer processing times, set the following properties for the config object.

// Connection timeout
connectTimeout := 60000
config.ConnectTimeout = &connectTimeout
// Read timeout
readTimeout := 60000
config.ReadTimeout = &readTimeout

For a list of all Document Intelligence OpenAPIs, see API Overview.

Submit with a local file

The APIs for converting images to Word, Excel, or PDF formats do not support file uploads.

The following example shows how to call an asynchronous job API by uploading a local file.

import (
  "fmt"
  "os"

  openClient "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  "github.com/alibabacloud-go/docmind-api-20220711/client"
  "github.com/alibabacloud-go/tea-utils/v2/service"
  "github.com/aliyun/credentials-go/credentials"
)

func submit() {
  // The program automatically performs authentication by reading your AccessKey from your credentials.
  // Before you run this example, complete the "Configure authentication" step.
  // This example creates default access credentials from a configuration file.
  // Initialize the Credentials client with the default credentials.
  credential, err := credentials.NewCredential(nil)
  // Get the AccessKey ID from the credentials.
  accessKeyId, err := credential.GetAccessKeyId()
  // Get the AccessKey secret from the credentials.
  accessKeySecret, err := credential.GetAccessKeySecret()
  // The service endpoint. Both IPv4 and IPv6 are supported. For IPv6, use docmind-api-dualstack.cn-hangzhou.aliyuncs.com.
  var endpoint string = "docmind-api.cn-hangzhou.aliyuncs.com"
  config := openClient.Config{AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, Endpoint: &endpoint}
  
  // Initialize the client.
  cli, err := client.NewClient(&config)
  if err != nil {
    panic(err)
  }
  // Call the API by uploading a local file.
  filename := "D:\\example.pdf"
  f, err := os.Open(filename)
  if err != nil {
    panic(err)
  }
  // Initialize the API request.
  request := client.SubmitDocStructureJobAdvanceRequest{
    FileName:      &filename,
    FileUrlObject: f,
  }
  // Create a RuntimeObject instance and set runtime parameters.
  options := service.RuntimeOptions{}
  // Replace the parameters and method with those of your target asynchronous job API. This example uses the document parsing API.
  response, err := cli.SubmitDocStructureJobAdvance(&request, &options)
  if err != nil {
    panic(err)
  }
  // Print the result.
  fmt.Println(response.Body.String())
}

The following response is returned.

{
   "Data": {
      "Id": "docmind-20220919-7297****"
   },
   "RequestId": "82008844-B6BC-552A-9C74-B5276CE7****"
}

Submit with a file URL

The file URL must be a publicly accessible URL for download, without cross-origin restrictions or special escaped characters.

The following code example shows how to call an asynchronous job API by providing a file URL.

import (
  "fmt"

  openClient "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  "github.com/alibabacloud-go/docmind-api-20220711/client"
  "github.com/aliyun/credentials-go/credentials"
)

func submit(){
  // The program automatically performs authentication by reading your AccessKey from your credentials.
  // Before you run this example, complete the "Configure authentication" step.
  // This example creates default access credentials from a configuration file.
  // Initialize the Credentials client with the default credentials.
  credential, err := credentials.NewCredential(nil)
  // Get the AccessKey ID from the credentials.
  accessKeyId, err := credential.GetAccessKeyId()
  // Get the AccessKey secret from the credentials.
  accessKeySecret, err := credential.GetAccessKeySecret()
  // The service endpoint. Both IPv4 and IPv6 are supported. For IPv6, use docmind-api-dualstack.cn-hangzhou.aliyuncs.com.
  var endpoint string = "docmind-api.cn-hangzhou.aliyuncs.com"
  config := openClient.Config{AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, Endpoint: &endpoint}
  
  // Initialize the client.
  cli, err := client.NewClient(&config)
  if err != nil {
    panic(err)
  }
  // File URL
  fileURL := "https://example.com/example.pdf"
  // File name
  fileName := "example.pdf"
  // Initialize the API request.
  request := client.SubmitDocStructureJobRequest{
    FileUrl:  &fileURL,
    FileName: &fileName,
  }
  // Replace the parameters and method with those of your target asynchronous job API. This example uses the document parsing API.
  response, err := cli.SubmitDocStructureJob(&request)
  if err != nil {
    panic(err)
  }
  // Print the result.
  fmt.Println(response.Body.String())
}

The following response is returned.

{
   "Data": {
      "Id": "docmind-20220927-8cd8****"
   },
   "RequestId": "17D2C185-5959-5251-B9D2-558C5D79****"
}

Query job results

The result query API returns one of three job statuses: processing, succeeded, or failed.

The following code example shows how to call the result query API for a document parsing job. The process is similar for other jobs.

import (
  "fmt"
  
  openClient "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  "github.com/alibabacloud-go/docmind-api-20220711/client"
  "github.com/aliyun/credentials-go/credentials"
)

func submit(){
  // The program automatically performs authentication by reading your AccessKey from your credentials.
  // Before you run this example, complete the "Configure authentication" step.
  // This example creates default access credentials from a configuration file.
  // Initialize the Credentials client with the default credentials.
  credential, err := credentials.NewCredential(nil)
  // Get the AccessKey ID from the credentials.
  accessKeyId, err := credential.GetAccessKeyId()
  // Get the AccessKey secret from the credentials.
  accessKeySecret, err := credential.GetAccessKeySecret()
  // The service endpoint. Both IPv4 and IPv6 are supported. For IPv6, use docmind-api-dualstack.cn-hangzhou.aliyuncs.com.
  var endpoint string = "docmind-api.cn-hangzhou.aliyuncs.com"
  config := openClient.Config{AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, Endpoint: &endpoint}
  
  // Initialize the client.
  cli, err := client.NewClient(&config)
  if err != nil {
    panic(err)
  }
  id := "docmind-20220925-76b1****"
  // Call the query API.
  request := client.GetDocStructureResultRequest{Id: &id}
  response, err := cli.GetDocStructureResult(&request)
  if err != nil {
    panic(err)
  }
  // Print the query result.
  fmt.Println(response.Body.String())
// Note: The Go SDK encodes the ampersand (&) character in the returned URL as its Unicode equivalent, \u0026. You must manually decode \u0026 back to & to download the file from the URL.
// Example of a URL returned by the Go SDK: http://docmind-api-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/convert/docmind-20220927-87ad**/example.pdf?Expires=XX\u0026OSSAccessKeyId=YY\u0026Signature=ZZ
}

The following response indicates that the job is still processing. Because the Completed field is false, you must continue polling until Completed returns true or you exceed the maximum polling time.

{
  "RequestId": "2AABD2C2-D24F-12F7-875D-683A27C3****",
  "Completed": false,
  "Code": "DocProcessing",
  "Message": "Document processing",
  "HostId": "ocr-api.cn-hangzhou.aliyuncs.com",
  "Recommend": "https://next.api.aliyun.com/troubleshoot?q=DocProcessing&product=docmind-api"
}

The following response shows a successful job. The Completed field is true, the Status field is Success, and the detailed results are in the Data node.

{
  "Status": "Success",
  "RequestId": "73134E1A-E281-1B2C-A105-D0EF****",
  "Completed": true,
	"Data": {
		"styles": [{
				"styleId": 0,
				"underline": false,
				"deleteLine": false,
				"bold": true,
				"italic": false,
				"fontSize": 15,
				"fontName": "黑体",
				"color": "000000",
				"charScale": 0.95
			},
			{
				"styleId": 1,
				"underline": false,
				"deleteLine": false,
				"bold": false,
				"italic": false,
				"fontSize": 12,
				"fontName": "微软雅黑",
				"color": "000000",
				"charScale": 1
			}
		],
		"layouts": [{
			"text": "测试标题",
			"index": 0,
			"uniqueId": "xxxx9816e77caea338df554b80ab95c7",
			"alignment": "center",
			"pageNum": [
				0
			],
			"pos": [{
					"x": 405,
					"y": 192
				},
				{
					"x": 860,
					"y": 191
				},
				{
					"x": 860,
					"y": 236
				},
				{
					"x": 406,
					"y": 237
				}
			],
			"type": "title",
      "subType":"doc_title"
		}, {
			"text": "本段为测试内容",
			"index": 1,
			"uniqueId": "xxxx8606c213c01c12d70f98dcfb2525",
			"alignment": "left",
			"pageNum": [
				0
			],
			"pos": [{
					"x": 187,
					"y": 311
				},
				{
					"x": 1075,
					"y": 311
				},
				{
					"x": 1076,
					"y": 373
				},
				{
					"x": 187,
					"y": 373
				}
			],
			"type": "text",
      "subType":"para",
			"lineHeight": 7,
			"firstLinesChars": 30,
			"blocks": [{
					"text": "本段",
					"pos": null,
					"styleId": 0
				},
				{
					"text": "为测试内容",
					"pos": null,
					"styleId": 1
				}
			]
		}],
		"logics": {
			"docTree": [{
				"uniqueId": "xxxx9816e77caea338df554b80ab95c7",
				"level": 0,
				"link": {
					"下级": [

					],
					"包含": [

					]
				},
				"backlink": {
					"上级": [
						"ROOT"
					]
				}
			}],
			"paragraphKVs": null,
			"tableKVs": null
		},
		"docInfo": {
			"docType": "pdf",
			"orignalDocName": "1.pdf",
			"pages": [{
				"imageType": "JPEG",
				"imageURL": "http://test.moshi.aliyuncs.com/docMind/image/xxxx3cccbfec45b48d3a8081c9c9659e/0",
				"angle": null,
				"imageWidth": 1273,
				"imageHeight": 1801,
				"pageIdCurDoc": 1,
				"pageIdAllDocs": 1
			}]
		}
	}
}

The following response shows a failed job. The Completed field is true, and the Status field is Fail. The response also includes an error code (Code) and a detailed message (Message). For more information about error codes, see Error Codes.

{
  "RequestId": "A8EF3A36-1380-1116-A39E-B377BE27****",
  "Completed": true,
  "Status": "Fail",
  "Code": "UrlNotLegal",
  "Message": "Failed to process the document.  The document url you provided is not legal.",
  "HostId": "docmind-api.cn-hangzhou.aliyuncs.com",
  "Recommend": "https://next.api.aliyun.com/troubleshoot?q=IDP.UrlNotLegal&product=docmind-api"
}