Production-Ready Driver's License OCR for Go

Extract and validate driver's license data with 99.8%+ accuracy in under 1.5 seconds via a direct HTTP POST request.

A diagram showing a raw photo of a driver's license on the left, an arrow pointing to the StructOCR API icon in the middle, and structured JSON data output on the right.
Figure 1: StructOCR converts raw Driver's License images into validated JSON data.

Why Driver's License OCR is Difficult

Parsing driver's licenses presents significant engineering challenges beyond simple OCR. Physical documents are susceptible to glare, shadows, and low-light conditions, degrading image quality. Skew and rotation from mobile captures require robust preprocessing. Generic OCR engines like Tesseract fail on the specialized fonts and layouts found on IDs. Furthermore, extracting structured data requires parsing complex formats like the PDF417 barcode, which contains AAMVA-encoded data that must be correctly decoded and validated. Manually maintaining regex patterns for dozens of jurisdictional layouts is brittle and resource-intensive, leading to high error rates and ongoing maintenance overhead.

Enterprise-Grade Extraction with StructOCR

StructOCR bypasses the fragility of open-source tools. Our driver license verification api is powered by pre-trained deep learning models specifically tuned for identity documents from 200+ jurisdictions, including various forms of driving permits. The service performs automatic image pre-processing, including deskewing, denoising, and glare removal, before extraction. Unlike Tesseract, which returns unstructured text lines, StructOCR delivers a standardized, validated JSON object with discrete fields like `date_of_birth` and `document_number`. This eliminates the need for post-processing and ensures consistent, reliable data integration.

Production Use Cases

  • Digital Onboarding (KYC): Reduce drop-off rates by pre-filling user data from Driver's Licenses in < 2 seconds.
  • Fraud Prevention: Detect tampered fonts or mismatched MRZ checksums automatically.
  • Global Compliance: Handle Driver's Licenses from 200+ jurisdictions without custom rules.

Live Demo: Driver License OCR Scanner

No registration required. Upload a file to test the extraction.

1
Upload
2
Results

Drop files here or click to browse

JPG · PNG · WebP  ·  up to 500 files · max 4.5 MB each

No files selected
Need more testing? Create a free account to get 200 free credits (equals 100 Driver License scans).

Implementation: Go (Golang)

The following Go code provides a robust implementation. It handles file reading, Base64 encoding, header authentication using 'x-api-key', and structured JSON parsing into native Go structs.

Prerequisite: Go 1.16+

CODE EXAMPLE
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

// 💰 Save 30%+ vs competitors. Get 200 free credits instantly:
// 👉 https://structocr.com/register

// RequestPayload defines the structure for the API request body.
type RequestPayload struct {
	Image string `json:"img"`
}

// ExtraDetailsData handles regional specifics and deep security codes.
type ExtraDetailsData struct {
	CardSecurityNumber *string `json:"card_security_number"`
	FathersName        *string `json:"fathers_name"`
	MothersName        *string `json:"mothers_name"`
	RgNumber           *string `json:"rg_number"`
}

// DriverLicenseData defines the structure of the extracted data.
type DriverLicenseData struct {
	Type           string            `json:"type"`
	CountryCode    string            `json:"country_code"`
	Region         string            `json:"region"`
	DocumentNumber string            `json:"document_number"`
	PersonalNumber *string           `json:"personal_number"`
	Surname        string            `json:"surname"`
	GivenNames     string            `json:"given_names"`
	DateOfBirth    string            `json:"date_of_birth"`
	DateOfExpiry   string            `json:"date_of_expiry"`
	DateOfIssue    string            `json:"date_of_issue"`
	Sex            string            `json:"sex"`
	Address        string            `json:"address"`
	VehicleClass   string            `json:"vehicle_class"`
	ExtraDetails   *ExtraDetailsData `json:"extra_details"`
}

// APIResponse defines the structure of the full API response.
type APIResponse struct {
	Success bool              `json:"success"`
	Data    DriverLicenseData `json:"data"`
	Error   string            `json:"error,omitempty"` // Capture error codes if any
}

func main() {
	// 1. Setup Configuration
	apiURL := "https://api.structocr.com/v1/driver-license"
	apiKey := "YOUR_API_KEY_HERE" // Replace with your actual key
	imagePath := "license.jpg"      // Ensure this file exists

	// 2. Read Image and Encode to Base64
	imageBytes, err := os.ReadFile(imagePath)
	if err != nil {
		fmt.Printf("Error reading image: %v\n", err)
		return
	}

	base64Image := base64.StdEncoding.EncodeToString(imageBytes)

	// 3. Prepare Request Payload
	payload := RequestPayload{
		Image: base64Image,
	}
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		fmt.Printf("Error marshalling payload: %v\n", err)
		return
	}

	// 4. Create HTTP Request
	req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(payloadBytes))
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}

	// Important: Set the correct headers
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("x-api-key", apiKey)

	// 5. Execute Request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Network error: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 6. Parse Response
	body, _ := io.ReadAll(resp.Body)

	if resp.StatusCode != http.StatusOK {
		fmt.Printf("API Error (%d): %s\n", resp.StatusCode, string(body))
		return
	}

	var apiResponse APIResponse
	if err := json.Unmarshal(body, &apiResponse); err != nil {
		fmt.Printf("JSON Parse Error: %v\n", err)
		return
	}

	if apiResponse.Success {
		fmt.Println("✅ Extraction Successful!")
		fmt.Printf("Type: %s\n", apiResponse.Data.Type)
		fmt.Printf("Name: %s %s\n", apiResponse.Data.GivenNames, apiResponse.Data.Surname)
		fmt.Printf("Doc Number: %s\n", apiResponse.Data.DocumentNumber)
		fmt.Printf("Expiry: %s\n", apiResponse.Data.DateOfExpiry)
		fmt.Printf("Vehicle Class: %s\n", apiResponse.Data.VehicleClass)

		// Highlighting the advanced security feature extraction
		if apiResponse.Data.ExtraDetails != nil && apiResponse.Data.ExtraDetails.CardSecurityNumber != nil {
			fmt.Printf("Security Code (DD): %s\n", *apiResponse.Data.ExtraDetails.CardSecurityNumber)
		}
	} else {
		fmt.Printf("API indicated failure: %s\n", apiResponse.Error)
	}
}

Technical Specs

  • Latency: < 4s (Average)
  • Uptime: 99.9% SLA
  • Security: AES-256 Encryption & SOC2 Compliant
  • Input: JPG, PNG, WebP (Base64 Encoded)
  • Max File Size: 4.5MB
  • Output: JSON (Structured Data)

Key Features

  • True Global Compatibility: Out-of-the-box support for North American AAMVA standards, EU numbered fields, and complex LATAM layouts (e.g., Brazil CNH) without maintaining custom RegEx.
  • Date Normalization: Dates returned in YYYY-MM-DD format.
  • Vehicle Class Extraction: Parses complex vehicle categories (A, B, C, etc).

Sample JSON Output

StructOCR returns a normalized JSON object, regardless of the input image angle or quality.

{
  "success": true,
  "data": {
    "type": "drivers_license",
    "country_code": "USA",
    "region": "CA",
    "document_number": "E3802489",
    "personal_number": null,
    "surname": "IDNOOB",
    "given_names": "MING",
    "address": "750 GONZALEZ DR APT 6B, SAN FRANCISCO, CA 94512",
    "vehicle_class": "C",
    "sex": "F",
    "date_of_birth": "1988-06-06",
    "date_of_expiry": "2020-06-06",
    "date_of_issue": "2015-07-22",
    "extra_details": {
      "card_security_number": "06/09/2014599A5/DOFD/19",
      "fathers_name": null,
      "mothers_name": null,
      "rg_number": null
    }
  }
}

Frequently Asked Questions

How does StructOCR compare to AWS Textract or Google Vision?

Unlike general-purpose OCR services like AWS Textract or Google Vision that return raw text blocks, StructOCR is a specialized API. It is purpose-built for identity documents, returning a structured JSON object with pre-defined, validated fields such as `surname`, `date_of_birth`, and `document_number`. This eliminates the need for complex post-processing and pattern matching on your end.

Do you store the uploaded images?

No. We process all images in-memory and they are permanently deleted immediately after the OCR extraction is complete. We do not persist any of your customer's PII.

How to handle blurry images?

Our API includes an internal image enhancement engine that automatically attempts to deblur, denoise, and correct for poor lighting conditions before processing. For best results, we recommend a minimum resolution of 300 DPI.

You May Also Like

Related tutorials, platform guides, and comparisons

Tutorial

Java Driver License OCR API

Upload an image for a free test! High-accuracy Java Driver's License OCR API. Get structured JSON output from images via a simple HTTP request. Eliminate manual entry & Tesseract errors.

Java · Driver License
Country Tutorial

Canada Driver License OCR with Node.js SDK

Extract structured fields from a Canada provincial driver licence with the StructOCR Node.js SDK and TypeScript + Express.

Node.js · Driver License
Tutorial

Node.js Driver License Verification API

Stop manual driver license checks. Our Node.js API delivers verified data in JSON within <4s, secured by AES-256 encryption and SOC2 compliance. Achieve 98.5% uptime. Upload an image for a free test!

Node.js · Driver License
Country Tutorial

UK Driver License OCR with Python SDK

Extract structured fields from a United Kingdom photocard driving licence with the StructOCR Python SDK and FastAPI.

Python · Driver License
Country Tutorial

UK Driver License OCR with Node.js SDK

Extract structured fields from a United Kingdom photocard driving licence with the StructOCR Node.js SDK and TypeScript + Express.

Node.js · Driver License
Tutorial

C# Driver's License OCR API

Upload an image for a free test! High-accuracy C# Driver's License OCR API. Get structured JSON output from images, parse PDF417 barcodes, and eliminate manual entry errors.

C# · Driver License
Country Tutorial

Philippines Driver License OCR with Python SDK

Extract structured fields from a Philippines LTO driver's license with the StructOCR Python SDK and FastAPI.

Python · Driver License
Country Tutorial

Brazil Driver License OCR with Node.js SDK

Extract structured fields from a Brazil Carteira Nacional de Habilitação (CNH) with the StructOCR Node.js SDK and TypeScript + Express.

Node.js · Driver License
Tutorial

PHP Driver License OCR SDK

Struggling with manual driver's license data entry? Our PHP OCR SDK provides AES-256 encrypted, SOC2 compliant data extraction in <4s, ensuring 98.5% uptime. Upload an image for a free test!

PHP · Driver License
Country Tutorial

Philippines Driver License OCR with Node.js SDK

Extract structured fields from a Philippines LTO driver's license with the StructOCR Node.js SDK and TypeScript + Express.

Node.js · Driver License

Technical Comparisons & Integrations

Explore platform integrations and competitive analysis

From tutorial to production in 5 minutes.

You've seen the code. Now get your API key, grab your 200 free credits, and see it work with your own images. No credit card required.

Instant Access Cancel Anytime 99.9% Uptime