Go language: REST Web service invocation

Source: Internet
Author: User
Tags http post package json
This is a creation in Article, where the information may have evolved or changed.

Dynamsoft deploys a rest-based barcode service. Here's how to use the Go language to send HTTP POST requests that contain BASE64 image data.

Environment configuration

    • Ide:jetbrain Gogland.
    • Go 1.7.4.
    • Windows 10.
    • Working directory Structure:
      <GOPATH>    - src    - bin    - pkg

    • Go settings:
      GOROOT=E:\GoGOPATH=g:\gowork

Basic steps

1. Read the image file.

2. Convert a byte array to a Base64 string.

3. JSON encoding.

4. Send JSON data via HTTP POST.

5. The server identifies the barcode and returns the result.

6. JSON decoding gets the result.

File read and BASE64 conversion

To read a file using the package Ioutil:

import "io/ioutil"data, err := ioutil.ReadFile(filename)

BASE64 encoding. Because I/O is more time-consuming, it can be put into goroutine to execute. Return results via Channel:

import "encoding/base64"channel <- base64.StdEncoding.EncodeToString(data)

JSON codec

First, store the data in map:

base64data := <-channeldata := make(map[string]interface{})data["image"] = base64datadata["barcodeFormat"] = 234882047data["maxNumPerPage"] = 1

Using the package JSON encoding:

jsonData, err := json.Marshal(data)

Returns the result JSON decoding:

result, _ := ioutil.ReadAll(resp.Body) // decode JSONconst resultKey = "displayValue"dec := json.NewDecoder(bytes.NewReader(result))for {    t, err := dec.Token()    if err == io.EOF {        break    }    if err != nil {        log.Fatal(err)    }    tmp := fmt.Sprintf("%v", t)    if tmp == resultKey {        t, _ := dec.Token()        tmp := fmt.Sprintf("%v", t)        fmt.Println("Barcode result: ", tmp)        break    }}

HTTP POST Request

To send an HTTP POST request using package http:

import "net/http"url := "http://demo1.dynamsoft.com/dbr/webservice/BarcodeReaderService.svc/Read"resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))

Test

1. Get the Dependency package:

go get github.com/dynamsoft-dbr/golang/web-service

2. Import dependencies in the Go project:

import "github.com/dynamsoft-dbr/golang/web-service"

3. Create Main.go:

package main import (    "os"    "fmt"    "github.com/dynamsoft-dbr/golang/web-service") func main()  {    var filename string    if len(os.Args) == 1 {        fmt.Println("Please specify a file.")        return    }    filename = os.Args[1]     _, err := os.Stat(filename)     if err != nil {        fmt.Println(err)        fmt.Println("Please specify a vailid file name.")        return    }     channel := make(chan string)    // read file to base64    go web_service.File2Base64(filename, channel)    // read barcode with Dynamsoft web service    web_service.ReadBarcode(channel)    fmt.Println("Done.")}

4. Compile and run the program:

go install<GOPATH>/bin/main <barcode image file>

Source

Https://github.com/dynamsoft-dbr/golang

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.