HTTP POST Request with Base64 Barcode Image in Golang

Dynamsoft has deployed a REST web service for barcode detection. This post shares how to call the service by sending HTTP POST request using Golang.

golang barcode web service

Barcode Detection in Golang

Environment

  • IDE: JetBrain Gogland.
  • Go 1.7.4.
  • Windows 10.
  • Workspace structure:

      <GOPATH>
          - src
          - bin
          - pkg
        
    
  • Settings:

      GOROOT=E:\Go
      GOPATH=g:\gowork
    

Basic Steps to Call Barcode Web Service

  1. Read an image file as bytes.
  2. Convert the bytes to a base64 string.
  3. Encode the base64 string as JSON string.
  4. Send HTTP POST request with JSON.
  5. Get HTTP response.
  6. Decode response body as JSON and get the barcode detection result.

Read File and Encode as Base64

Read an image file as bytes with Package ioutil:

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

Encode bytes as base64 with Package base64. When using goroutine for I/O, you can use a channel to send and receive values:

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

Encode and Decode JSON

Store data in a map:

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

Generate the JSON encoding of the map with Package json:

jsonData, err := json.Marshal(data)

Decode JSON to get the barcode result with Token:

result, _ := ioutil.ReadAll(resp.Body)

// decode JSON
const 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

Send HTTP request with 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))

Demo

  1. Get the package:

     go get github.com/dynamsoft-dbr/golang/web-service
    
  2. Import the package to a 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. Build and run the console app:

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

    golang barcode result

Source Code

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