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
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