Go में Base64 डिकोड करें — encoding/base64 गाइड + उदाहरण

·Systems Engineer·समीक्षकHana Nováková·प्रकाशित

मुफ़्त Base64 Decode Online को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।

Base64 Decode Online ऑनलाइन आज़माएं →

Go में Base64 डीकोडिंग बहुत common task है — JWT inspection, binary file attachments, cloud services से आने वाले API payloads। Go का standard encoding/base64पैकेज यह सब handle करता है, लेकिन गलत encoding variant चुनना (standard बनाम URL-safe, padded बनाम unpadded) “illegal base64 data” एरर का सबसे आम कारण है। यह गाइड StdEncoding, URLEncoding, RawURLEncoding, streaming decoding with base64.NewDecoder, JWT payload inspection, और चार सामान्य गलतियों को cover करती है। ब्राउज़र में बस एक बार decode करना हो तो ToolDeck का Base64 डिकोडर बिना एक भी लाइन कोड लिखे तुरंत काम करता है।

  • encoding/base64 Go standard library का हिस्सा है — go get की जरूरत नहीं
  • JWT टोकन और अधिकांश आधुनिक API के लिए RawURLEncoding उपयोग करें (बिना पैडिंग, URL-safe अल्फाबेट)
  • StdEncoding, + और / के साथ = पैडिंग उपयोग करता है; URLEncoding - और _ में बदल देता है लेकिन पैडिंग रखता है
  • base64.NewDecoder किसी भी io.Reader को रैप करता है, मेमोरी में लोड किए बिना streaming decode के लिए
  • हमेशा returned error जाँचें — invalid padding और गलत अल्फाबेट illegal base64 data एरर देते हैं

Base64 डीकोडिंग क्या है?

Base64 encoding, binary data को 64 printable characters (A–Z, a–z, 0–9, और दो extra characters) का उपयोग करके ASCII text के रूप में represent करती है। Decoding इसे reverse करता है — ASCII representation को वापस original bytes में convert करता है। हर 4 Base64 characters ठीक 3 bytes में decode होते हैं। इसकी ज़रूरत इसलिए है क्योंकि कई transport layers (email, HTTP headers, JSON fields) text के लिए designed हैं, raw binary के लिए नहीं। नीचे round-trip का उदाहरण है:

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	// Raw bytes → Base64 encoded → decoded back to raw bytes
	original := []byte("service_token:xK9mP2qR")
	// Encoded: "c2VydmljZV90b2tlbjp4SzltUDJxUg=="

	encoded := base64.StdEncoding.EncodeToString(original)
	decoded, _ := base64.StdEncoding.DecodeString(encoded)
	fmt.Println(string(decoded) == string(original)) // true
}

encoding/base64 से Go में Base64 डीकोड करें

encoding/base64 पैकेज Go के साथ आता है — कोई external dependency नहीं। यह package-level variables के रूप में चार pre-defined encoding variants expose करता है। strings के लिए सबसे common function DecodeString है, जो byte slice और error रिटर्न करती है।

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
	"log"
)

func main() {
	// Standard Base64 — the alphabet uses + and / with = padding
	encoded := "eyJob3N0IjoiZGItcHJvZC51cy1lYXN0LTEiLCJwb3J0Ijo1NDMyfQ=="
	decoded, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		log.Fatalf("decode error: %v", err)
	}
	fmt.Println(string(decoded))
	// {"host":"db-prod.us-east-1","port":5432}
}

Decode मेथड strings की जगह byte slices पर काम करता है, और result को एक pre-allocated destination buffer में लिखता है। Buffer को सही आकार देना जरूरी है — अधिकतम आकार पाने के लिए base64.StdEncoding.DecodedLen(len(src)) उपयोग करें (पैडिंग के कारण यह actual decoded length से कुछ bytes बड़ा हो सकता है)।

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
	"log"
)

func main() {
	src := []byte("eyJob3N0IjoiZGItcHJvZCIsInBvcnQiOjU0MzJ9")
	dst := make([]byte, base64.RawStdEncoding.DecodedLen(len(src)))

	n, err := base64.RawStdEncoding.Decode(dst, src)
	if err != nil {
		log.Fatalf("decode: %v", err)
	}
	fmt.Println(string(dst[:n]))
	// {"host":"db-prod","port":5432}
}
नोट:DecodedLen upper bound रिटर्न करता है, exact length नहीं। result को सही तरीके से slice करने के लिए हमेशा Decode से मिले n return value का उपयोग करें: dst[:n]

StdEncoding बनाम URLEncoding — सही Variant चुनना

यहीं पर सबसे ज्यादा confusion होती है। Go के encoding/base64 में चार encoding objects हैं, और गलत चुनने पर हमेशा error आएगी। अंतर दो चीजों पर निर्भर करता है: अल्फाबेट और पैडिंग।

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	// JWT header payload — URL-safe, no padding
	jwtHeader := "eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMjMtMDkifQ"

	// Wrong: StdEncoding fails on URL-safe input without padding
	_, err1 := base64.StdEncoding.DecodeString(jwtHeader)
	fmt.Println("StdEncoding error:", err1)
	// StdEncoding error: illegal base64 data at input byte 43

	// Correct: RawURLEncoding — no padding, URL-safe alphabet
	decoded, err2 := base64.RawURLEncoding.DecodeString(jwtHeader)
	fmt.Println("RawURLEncoding ok:", err2, "→", string(decoded))
	// RawURLEncoding ok: <nil> → {"alg":"RS256","kid":"2023-09"}
}

एक नज़र में चारों variants:

फ़ंक्शन / मेथड
एन्कोडिंग
पैडिंग आवश्यक
रिटर्न करता है
base64.StdEncoding.DecodeString(s)
Standard (+, /)
हाँ (=)
([]byte, error)
base64.URLEncoding.DecodeString(s)
URL-safe (-, _)
हाँ (=)
([]byte, error)
base64.RawStdEncoding.DecodeString(s)
Standard (+, /)
नहीं
([]byte, error)
base64.RawURLEncoding.DecodeString(s)
URL-safe (-, _)
नहीं
([]byte, error)
base64.StdEncoding.Decode(dst, src)
Standard (+, /)
हाँ (=)
(n int, error)
base64.NewDecoder(enc, r)
कोई भी एन्कोडिंग
हाँ
io.Reader

मेरा rule of thumb: अगर यह JWT, OAuth flow, या cloud provider SDK से आया है, तो पहले RawURLEncoding आज़माएं। अगर email attachments या पुराने web forms से आया है, तो StdEncoding try करें। error message हमेशा वह exact byte position बताती है जहाँ decoding fail हुई।

File और API Response से Base64 डीकोड करना

Base64-encoded फ़ाइल पढ़ना

Binary files (images, PDFs, certificates) कभी-कभी disk पर Base64-encoded रूप में store होती हैं। फ़ाइल पढ़ें, trailing whitespace हटाएं, फिर decode करें:

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
	"log"
	"os"
	"strings"
)

func main() {
	raw, err := os.ReadFile("certificate.pem.b64")
	if err != nil {
		log.Fatalf("read file: %v", err)
	}

	// Strip newlines — Base64 files often have line breaks every 76 chars
	cleaned := strings.ReplaceAll(strings.TrimSpace(string(raw)), "\n", "")

	decoded, err := base64.StdEncoding.DecodeString(cleaned)
	if err != nil {
		log.Fatalf("decode: %v", err)
	}

	if err := os.WriteFile("certificate.pem", decoded, 0600); err != nil {
		log.Fatalf("write: %v", err)
	}
	fmt.Printf("decoded %d bytes → certificate.pem\n", len(decoded))
}

API JSON response से Base64 field डीकोड करना

Cloud APIs अक्सर binary data (encryption keys, signed blobs, thumbnails) को JSON के अंदर Base64 strings के रूप में return करते हैं। पहले JSON unmarshal करें, फिर target field decode करें:

Go 1.21+
package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type SecretResponse struct {
	Name    string `json:"name"`
	Payload string `json:"payload"` // Base64-encoded secret value
	Version int    `json:"version"`
}

func fetchAndDecodeSecret(secretURL string) ([]byte, error) {
	resp, err := http.Get(secretURL)
	if err != nil {
		return nil, fmt.Errorf("http get: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)
	}

	var secret SecretResponse
	if err := json.NewDecoder(resp.Body).Decode(&secret); err != nil {
		return nil, fmt.Errorf("decode json: %w", err)
	}

	value, err := base64.StdEncoding.DecodeString(secret.Payload)
	if err != nil {
		return nil, fmt.Errorf("decode base64: %w", err)
	}
	return value, nil
}

func main() {
	value, err := fetchAndDecodeSecret("https://api.example.com/secrets/db-password")
	if err != nil {
		log.Fatalf("fetch secret: %v", err)
	}
	fmt.Printf("secret value: %s\n", value)
}
नोट:context खोने की बजाय errors को fmt.Errorf("decode base64: %w", err) से wrap करें। encoding/base64 का original error message failure का exact byte position बताता है, जो debugging के दौरान उपयोगी होता है।

बड़ी Base64-encoded Files की Streaming

500 MB Base64-encoded फ़ाइल को os.ReadFile से मेमोरी में लोड करके DecodeString call करने में लगभग 750 MB RAM लगती है (encoded string plus decoded bytes)। base64.NewDecoder किसी भी io.Reader को रैप करता है और chunks में decode करता है, जिससे memory usage लगभग constant रहती है। clean streaming pipeline के लिए इसे io.Copy के साथ combine करें:

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
	"io"
	"log"
	"os"
)

func streamDecodeFile(srcPath, dstPath string) error {
	src, err := os.Open(srcPath)
	if err != nil {
		return fmt.Errorf("open source: %w", err)
	}
	defer src.Close()

	dst, err := os.Create(dstPath)
	if err != nil {
		return fmt.Errorf("create dest: %w", err)
	}
	defer dst.Close()

	decoder := base64.NewDecoder(base64.StdEncoding, src)
	written, err := io.Copy(dst, decoder)
	if err != nil {
		return fmt.Errorf("stream decode: %w", err)
	}
	fmt.Printf("written %d bytes to %s\n", written, dstPath)
	return nil
}

func main() {
	if err := streamDecodeFile("backup.tar.b64", "backup.tar"); err != nil {
		log.Fatal(err)
	}
}
चेतावनी:base64.NewDecoder साफ, बिना interruption के Base64 data expect करता है। अगर source file में line breaks हैं (PEM और MIME-encoded files में सामान्य), तो streaming से पहले source reader को line-stripping reader से wrap करें या फ़ाइल से newlines pre-process करके हटाएं।

Command Line से Base64 डीकोडिंग

अधिकांश Go developers debugging के समय पहले command line उपयोग करते हैं। हर macOS और Linux सिस्टम में base64 होता है; Windows पर PowerShell में built-in equivalent है। API payloads को जल्दी inspect करने के लिए ये Go script लिखने से तेज़ हैं।

bash
# Decode a Base64 string (Linux / macOS)
echo "eyJob3N0IjoiZGItcHJvZCIsInBvcnQiOjU0MzJ9" | base64 --decode
# {"host":"db-prod","port":5432}

# Decode and pretty-print with jq (pipe the JSON output)
echo "eyJob3N0IjoiZGItcHJvZCIsInBvcnQiOjU0MzJ9" | base64 --decode | jq .
# {
#   "host": "db-prod",
#   "port": 5432
# }

# Decode a Base64-encoded file to binary
base64 --decode < encrypted_payload.b64 > encrypted_payload.bin

# macOS uses -D flag instead of --decode
echo "c2VjcmV0LXRva2Vu" | base64 -D

बिना कोई tool install किए JWT tokens inspect करने के लिए, token को ToolDeck के Base64 डिकोडर में paste करें — dots पर split करें और हर part को decode करें।

High-Performance Alternative: encoding/base64 पहले से ही तेज़ है

Python के विपरीत, जहाँ orjson बनाम json एक meaningful performance conversation है, Go का encoding/base64 पहले से assembly-optimized है और ज़्यादातर cases के लिए genuinely fast है। फिर भी, अगर आप tight loop में millions of records process कर रहे हैं, तो filippo.io/base64 drop-in API के साथ SIMD-accelerated decoding provide करता है।

bash
go get filippo.io/base64
Go 1.21+
package main

import (
	"fmt"
	"log"

	"filippo.io/base64"
)

func main() {
	// Drop-in replacement — same API as encoding/base64
	encoded := "eyJob3N0IjoiY2FjaGUtcHJvZCIsInBvcnQiOjYzNzl9"
	decoded, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		log.Fatalf("decode: %v", err)
	}
	fmt.Println(string(decoded))
	// {"host":"cache-prod","port":6379}
}

Performance gain AVX2 support के साथ amd64 पर सबसे ज्यादा दिखता है — benchmarks बड़े inputs पर 2–4x throughput improvement दिखाते हैं। Normal API responses (एक बार में कुछ सौ bytes) के लिए standard library ही काफ़ी है।

Go में Base64 JWT Payload डीकोड करना

JWT inspection लगभग हर backend service में आता है। मेरे अनुभव में, अधिकांश debugging sessions “इस token में actually क्या है?” तक पहुँचती हैं — और आप बिना full JWT library लाए इसका जवाब दे सकते हैं। Token में dots से separated तीन Base64url-encoded segments होते हैं। बीच का segment वह payload है जिसकी आपको जरूरत है:

Go 1.21+
package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"strings"
)

type JWTPayload struct {
	Subject  string   `json:"sub"`
	Issuer   string   `json:"iss"`
	Expiry   int64    `json:"exp"`
	Roles    []string `json:"roles"`
}

func decodeJWTPayload(token string) (*JWTPayload, error) {
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		return nil, fmt.Errorf("invalid JWT: expected 3 segments, got %d", len(parts))
	}

	// JWT uses RawURLEncoding — URL-safe alphabet, no = padding
	raw, err := base64.RawURLEncoding.DecodeString(parts[1])
	if err != nil {
		return nil, fmt.Errorf("decode payload: %w", err)
	}

	var payload JWTPayload
	if err := json.Unmarshal(raw, &payload); err != nil {
		return nil, fmt.Errorf("unmarshal payload: %w", err)
	}
	return &payload, nil
}

func main() {
	token := "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c3ItNDQyIiwiaXNzIjoiYXV0aC5leGFtcGxlLmNvbSIsImV4cCI6MTc0MTk1NjgwMCwicm9sZXMiOlsiYWRtaW4iLCJhdWRpdG9yIl19.SIGNATURE"

	payload, err := decodeJWTPayload(token)
	if err != nil {
		log.Fatalf("jwt: %v", err)
	}
	fmt.Printf("Subject: %s\n", payload.Subject)
	fmt.Printf("Issuer:  %s\n", payload.Issuer)
	fmt.Printf("Roles:   %v\n", payload.Roles)
	// Subject: usr-442
	// Issuer:  auth.example.com
	// Roles:   [admin auditor]
}

सामान्य गलतियाँ

मैंने real code reviews में ये चारों गलतियाँ देखी हैं — पहली दो तो लगभग हर बार तब आती हैं जब कोई नया auth provider integrate करता है।

URL-safe input पर StdEncoding का उपयोग

समस्या: JWT tokens और OAuth tokens URL-safe Base64 अल्फाबेट (- और _) उपयोग करते हैं। उन्हें StdEncoding.DecodeString को pass करने पर 'illegal base64 data' error आती है।

समाधान: अपना input source जाँचें: auth systems के tokens RawURLEncoding उपयोग करते हैं; binary attachments StdEncoding उपयोग करते हैं।

Before · Go
After · Go
// JWT header — URL-safe, no padding
token := "eyJhbGciOiJSUzI1NiJ9"
decoded, err := base64.StdEncoding.DecodeString(token)
// err: illegal base64 data at input byte 19
// JWT header — correct encoding
token := "eyJhbGciOiJSUzI1NiJ9"
decoded, err := base64.RawURLEncoding.DecodeString(token)
// decoded: {"alg":"RS256"}
// err: nil
Decode से n return value को ignore करना

समस्या: Decode एक pre-allocated buffer में लिखता है और actually लिखे गए bytes की संख्या return करता है। DecodedLen upper bound return करता है, इसलिए buffer के अंत में garbage bytes हो सकते हैं।

समाधान: हमेशा dst[:n] से result slice करें — dst[:len(dst)] से नहीं।

Before · Go
After · Go
dst := make([]byte, base64.StdEncoding.DecodedLen(len(src)))
base64.StdEncoding.Decode(dst, src)
fmt.Println(string(dst)) // may include trailing zero bytes
dst := make([]byte, base64.StdEncoding.DecodedLen(len(src)))
n, err := base64.StdEncoding.Decode(dst, src)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(dst[:n])) // correct — only the decoded bytes
Decode से पहले whitespace न हटाना

समस्या: Terminals, emails, या config files से copy की गई Base64 strings में अक्सर trailing newlines या spaces होते हैं। उन्हें directly DecodeString को pass करने पर whitespace character पर fail होती है।

समाधान: Decoding से पहले strings.TrimSpace (और embedded newlines के लिए strings.ReplaceAll) call करें।

Before · Go
After · Go
// Value read from a config file with a trailing newline
encoded := "c2VydmljZV9rZXk6eEtNcDI=\n"
decoded, err := base64.StdEncoding.DecodeString(encoded)
// err: illegal base64 data at input byte 24
encoded := "c2VydmljZV9rZXk6eEtNcDI=\n"
cleaned := strings.TrimSpace(encoded)
decoded, err := base64.StdEncoding.DecodeString(cleaned)
// decoded: "service_key:xKMp2"
// err: nil
Decoded bytes को गलत तरीके से string में store करना

समस्या: Binary data (images, compressed payloads) पर string(decoded) call करने से invalid UTF-8 strings बनती हैं। Go strings arbitrary bytes hold कर सकती हैं, लेकिन कुछ operations content को खराब कर देंगे।

समाधान: Binary data को पूरे pipeline में []byte के रूप में रखें। string(decoded) तभी call करें जब decoded content guaranteed text हो।

Before · Go
After · Go
decoded, _ := base64.StdEncoding.DecodeString(pngBase64)
// Treating binary PNG as a string loses data
imageStr := string(decoded)
os.WriteFile("image.png", []byte(imageStr), 0644) // may corrupt
decoded, err := base64.StdEncoding.DecodeString(pngBase64)
if err != nil {
    log.Fatal(err)
}
// Write bytes directly — no string conversion
os.WriteFile("image.png", decoded, 0644)

Method तुलना

सभी variants standard library में आते हैं — इनमें से किसी के लिए भी external dependencies नहीं हैं।

मेथड
इनपुट टाइप
एन्कोडिंग वेरिएंट
स्ट्रीमिंग
कस्टम अल्फाबेट
कस्टम पैडिंग
इंस्टॉल आवश्यक
StdEncoding.DecodeString
string
Standard
नहीं (stdlib)
URLEncoding.DecodeString
string
URL-safe
नहीं (stdlib)
RawStdEncoding.DecodeString
string
Standard (no pad)
नहीं (stdlib)
RawURLEncoding.DecodeString
string
URL-safe (no pad)
नहीं (stdlib)
StdEncoding.Decode
[]byte
Standard
नहीं (stdlib)
base64.NewDecoder
io.Reader
कोई भी
नहीं (stdlib)
encoding/base64 + NewEncoding
string
कस्टम अल्फाबेट
नहीं (stdlib)

JWT tokens और OAuth flows के लिए: RawURLEncoding। Email attachments और MIME data के लिए: StdEncoding। Disk या network से बड़ी binary files के लिए: reader को base64.NewDecoder में wrap करें — यह file size चाहे जितनी हो, memory use flat रखता है। Custom alphabet चाहिए? base64.NewEncoding(alphabet) special use cases के लिए नया encoding object बनाता है।

Development के दौरान quick one-off checks के लिए, ऑनलाइन Base64 डिकोडर Go program शुरू करने से तेज़ है।

अक्सर पूछे जाने वाले सवाल

Go में Base64 स्ट्रिंग को कैसे डीकोड करें?

encoding/base64 इम्पोर्ट करें और base64.StdEncoding.DecodeString(s) कॉल करें। यह ([]byte, error) रिटर्न करता है — error को हमेशा जाँचें। अगर स्ट्रिंग में URL-safe कैरेक्टर हैं (+ और / की जगह - और _), तो base64.URLEncoding.DecodeString उपयोग करें। JWT टोकन और अधिकांश आधुनिक API के लिए RawURLEncoding (बिना पैडिंग) सही विकल्प है।

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
	"log"
)

func main() {
	encoded := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
	decoded, err := base64.RawURLEncoding.DecodeString(encoded)
	if err != nil {
		log.Fatalf("decode: %v", err)
	}
	fmt.Println(string(decoded))
	// {"alg":"HS256","typ":"JWT"}
}

Go में StdEncoding और URLEncoding में क्या अंतर है?

StdEncoding, standard Base64 अल्फाबेट के साथ + और / कैरेक्टर और = पैडिंग का उपयोग करता है — RFC 4648 §4 में परिभाषित। URLEncoding, + को - से और / को _ से बदल देता है, जिससे आउटपुट URL और HTTP हेडर में percent-encoding के बिना सुरक्षित हो जाता है — RFC 4648 §5 में परिभाषित। JWT टोकन, OAuth टोकन और query string में एम्बेड किए गए डेटा के लिए URLEncoding उपयोग करें।

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	// Standard: may contain + / and = characters
	std := base64.StdEncoding.EncodeToString([]byte("hello/world"))
	fmt.Println(std) // "aGVsbG8vd29ybGQ="

	// URL-safe: replaces + with - and / with _
	url := base64.URLEncoding.EncodeToString([]byte("hello/world"))
	fmt.Println(url) // "aGVsbG8vd29ybGQ=" (same — diff shows with different bytes)

	// JWT headers never have padding — use RawURLEncoding
	raw := base64.RawURLEncoding.EncodeToString([]byte("hello/world"))
	fmt.Println(raw) // "aGVsbG8vd29ybGQ" (no trailing =)
}

Go में "illegal base64 data" एरर को कैसे ठीक करें?

इस एरर का मतलब है कि इनपुट में अपेक्षित अल्फाबेट से बाहर के कैरेक्टर हैं, या पैडिंग गलत है। तीन सामान्य कारण: URL-safe इनपुट पर StdEncoding का उपयोग (URLEncoding में बदलें), बिना पैडिंग वाले इनपुट पर padded encoder का उपयोग (RawStdEncoding/RawURLEncoding में बदलें), या trailing whitespace/newlines। डीकोडिंग से पहले strings.TrimSpace से whitespace हटाएं।

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
	"log"
	"strings"
)

func main() {
	// Input from a webhook payload — has newlines stripped from wire format
	raw := "  aGVsbG8gd29ybGQ=  \n"
	cleaned := strings.TrimSpace(raw)

	decoded, err := base64.StdEncoding.DecodeString(cleaned)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(decoded)) // hello world
}

Go में बड़ी Base64-encoded फ़ाइल को stream-decode कैसे करें?

base64.NewDecoder(base64.StdEncoding, reader) उपयोग करें जो किसी भी io.Reader को रैप करता है और on-the-fly डीकोड करता है। इसे io.Copy के माध्यम से destination पर लिखें बिना पूरी फ़ाइल को मेमोरी में बफर किए। यह Base64-encoded binary attachments या बड़े data payloads को डीकोड करने का standard pattern है।

Go 1.21+
package main

import (
	"encoding/base64"
	"io"
	"log"
	"os"
)

func main() {
	src, err := os.Open("attachment.b64")
	if err != nil {
		log.Fatal(err)
	}
	defer src.Close()

	dst, err := os.Create("attachment.bin")
	if err != nil {
		log.Fatal(err)
	}
	defer dst.Close()

	decoder := base64.NewDecoder(base64.StdEncoding, src)
	io.Copy(dst, decoder)
}

क्या Go में JWT library के बिना Base64 JWT payload को डीकोड किया जा सकता है?

हाँ। JWT में तीन Base64url-encoded segments होते हैं, dots (.) से अलग। "." पर split करें और दूसरे सेगमेंट (index 1) को base64.RawURLEncoding.DecodeString से डीकोड करें — JWT headers और payloads URL-safe अल्फाबेट और बिना पैडिंग के उपयोग करते हैं। signature सेगमेंट (index 2) binary होता है और आमतौर पर केवल verification के लिए जरूरी होता है।

Go 1.21+
package main

import (
	"encoding/base64"
	"fmt"
	"log"
	"strings"
)

func main() {
	token := "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c3ItOTAxIiwicm9sZSI6ImFkbWluIn0.SIG"
	parts := strings.Split(token, ".")
	if len(parts) < 2 {
		log.Fatal("invalid JWT format")
	}

	payload, err := base64.RawURLEncoding.DecodeString(parts[1])
	if err != nil {
		log.Fatalf("decode payload: %v", err)
	}
	fmt.Println(string(payload))
	// {"sub":"usr-901","role":"admin"}
}

HTTP API response से Base64 डेटा डीकोड करने के लिए कौन सी एन्कोडिंग उपयोग करें?

API docs जाँचें या encoded string को inspect करें। अगर इसमें + या / कैरेक्टर हैं और = से खत्म होती है, तो StdEncoding उपयोग करें। अगर इसमें - और _ कैरेक्टर हैं और = नहीं है, तो RawURLEncoding उपयोग करें। जब संदेह हो, पहले RawURLEncoding आज़माएं — अधिकांश आधुनिक API (OAuth2, JWT, Google Cloud, AWS) बिना पैडिंग के URL-safe Base64 उपयोग करते हैं।

Go 1.21+
package main

import (
	"encoding/base64"
	"strings"
)

// Detect encoding variant from the encoded string
func decodeAPIPayload(encoded string) ([]byte, error) {
	// URL-safe characters without padding — common in modern APIs
	if !strings.Contains(encoded, "+") && !strings.Contains(encoded, "/") {
		return base64.RawURLEncoding.DecodeString(encoded)
	}
	// Standard Base64 with padding
	return base64.StdEncoding.DecodeString(encoded)
}

संबंधित टूल्स

  • Base64 एनकोडर — ब्राउज़र में binary data या text को Base64 में encode करें, आपके Go unit tests में paste करने के लिए test fixtures generate करने में उपयोगी।
  • JWT डिकोडर — एक साथ तीनों JWT segments को split और decode करें, field-by-field payload inspection के साथ — जब debugging के दौरान बस token पढ़ना हो तो कोई Go code जरूरी नहीं।
  • URL डिकोडर — URL-encoded strings को percent-decode करें, जब API responses में Base64url data और percent-encoded query parameters दोनों मिले हों तो उपयोगी।
  • JSON फ़ॉर्मेटर — Base64 JWT payload या API response decode करने के बाद, JSON को यहाँ paste करें और structure को instantly pretty-print और validate करें।
इसमें भी उपलब्ध:JavaScriptPythonJavaC#
JO
James OkaforSystems Engineer

James is a systems engineer and Go enthusiast who focuses on high-performance microservices, command-line tooling, and infrastructure automation. He enjoys the simplicity and explicitness of Go and writes about building fast, reliable backend systems. When not coding he explores distributed systems concepts and contributes to open-source Go libraries.

HN
Hana Novákováतकनीकी समीक्षक

Hana is a backend engineer who has built production gRPC and REST services in Go for cloud-native environments. She cares deeply about API correctness, protobuf schema design, and the operational side of running Go services in Kubernetes. She writes about the Go standard library, encoding and marshalling patterns, gRPC best practices, and the subtleties of writing idiomatic Go that is easy to test and maintain.