Esta página ainda não está disponível no idioma selecionado. Estamos trabalhando para adicionar mais opções de idiomas. Agradecemos sua compreensão.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Go SDK

Updated on 2024-09-04 GMT+08:00

This section describes how to use the Go SDK to quickly develop OCR services.

Prerequisites

  • You have registered a Huawei ID and enabled Huawei Cloud services. Your account cannot be in arrears or frozen.
  • Go 1.14 or later is available. You can run the go version command to check the version information.
  • You have obtained an AK and an SK on the My Credentials > Access Keys page. The AK and SK are contained in the credentials.csv file.
    Figure 1 Creating an access key

  • You have obtained the IAM user name, account name, and the project ID of your target region on the My Credentials > API Credentials page. The information will be used during service calling. Save it in advance.
    Figure 2 API Credentials

Installing the SDK

Before you use the SDK, you need to install the Huawei Cloud Go SDK library.

// Install the Huawei Cloud Go SDK library.
go get github.com/huaweicloud/huaweicloud-sdk-go-v3

Getting Started

  1. Import dependency modules.
    import (
    "fmt"
    "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        ocr "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1"
    "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1/region"
    )
  2. Configure authentication information.

    Configure ak and sk. AK is used together with SK to sign requests cryptographically, ensuring that the requests are secret, complete, and correct. For details about how to obtain the AK and SK, see Prerequisites.

    func main() {
        ak := os.Getenv("HUAWEICLOUD_SDK_AK")
        sk := os.Getenv("HUAWEICLOUD_SDK_SK")
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            Build()
    }
    NOTE:
    • Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
    • In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
  3. Initialize the client (using either of the following methods).
    • (Recommended) Specifying a region for a cloud service
      // Initialize the client New{Service}Client of a specified cloud service. The following uses the AP-Bangkok region as an example.
      func main() {
          client := ocr.NewOcrClient(
              ocr.OcrClientBuilder().
                  WithRegion(region.ValueOf("ap-southeast-2")).
                  WithCredential(auth).
                  Build())
      }
    • Specifying an endpoint for a cloud service
      func main() {
          // Specify the endpoint for OCR, for example, AP-Bangkok.
          endpoint:="https://ocr.ap-southeast-2.myhuaweicloud.com"
          // If you choose to specify the endpoint, add projectId to the authentication information.
          auth := basic.NewCredentialsBuilder().
              WithAk(ak).
              WithSk(sk).
              WithProjectId(projectId).
              Build()
          // Initialize the client New{Service}Client of a specified cloud service.
          client := ocr.NewOcrClient(
              ocr.OcrClientBuilder().
                  WithEndpoint(endpoint).
                  WithCredential(auth).
                  Build())
      }

      endpoint indicates the endpoints for Huawei Cloud services. For details, see Regions and Endpoints.

  4. Send a request and check the response.
    // The following uses calling the RecognizePassport API of Passport OCR as an example.
    request := &model.RecognizePassportRequest{}
    urlPassportRequestBody:= "Image URL"
    request.Body = &model.PassportRequestBody{
    	Url: &urlPassportRequestBody,
    }
    response, err := client.RecognizePassport(request)
    if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
  5. Handle the exception.
    Table 1 Exception handling

    Level-1 Category

    Level-1 Category Description

    ServiceResponseError

    A service response exception occurs.

    url.Error

    A URL exception occurs.

    response, err := client.RecognizePassport(request)
    if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
NOTE:

For the SDK, see SDK Center and Go SDK Usage Guide.

Automatic Generation of Sample Code

API Explorer allows for API search and platform debugging, with features such as quick and comprehensive search, visual debugging, access to help documentation, and online consultation.

You only need to modify API parameters in the API Explorer to automatically generate the corresponding sample code.

Figure 3 API Explorer

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback