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


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

          - src
          - bin
          - pkg
  • Settings:


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 {
    if err != nil {
    tmp := fmt.Sprintf("%v", t)
    if tmp == resultKey {
        t, _ := dec.Token()
        tmp := fmt.Sprintf("%v", t)
        fmt.Println("Barcode result: ", tmp)


Send HTTP request with Package http:

import "net/http"
url := ""
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))


  1. Get the package:

     go get
  2. Import the package to a Go project:

     import ""
  3. Create main.go:

     package main
     import (
     func main()  {
         var filename string
         if len(os.Args) == 1 {
             fmt.Println("Please specify a file.")
         filename = os.Args[1]
         _, err := os.Stat(filename)
         if err != nil {
             fmt.Println("Please specify a vailid file name.")
         channel := make(chan string)
         // read file to base64
         go web_service.File2Base64(filename, channel)
         // read barcode with Dynamsoft web service
  4. Build and run the console app:

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

    golang barcode result

Source Code