encoding package defines interfaces for encoding and decoding. It contains subpackages for specific encoding formats.
Common Interface
Subpackages
encoding/json
JSON encoding and decoding.encoding/xml
XML encoding and decoding.encoding/csv
CSV (Comma-Separated Values) reading and writing.encoding/base64
Base64 encoding and decoding.encoding/hex
Hexadecimal encoding and decoding.encoding/binary
Binary encoding and decoding of numeric values.encoding/gob
Go-specific binary encoding.encoding/pem
PEM (Privacy Enhanced Mail) encoding.encoding/asn1
ASN.1 DER encoding and decoding.Practical Examples
JSON API Handler
Configuration File Parsing
CSV to JSON Converter
Binary Protocol
JSON Struct Tags
Best Practices
- Use streaming for large data - Use Encoder/Decoder instead of Marshal/Unmarshal
- Handle errors properly - Check all encoding/decoding errors
- Validate input - Don’t trust decoded data
- Use appropriate encoding - JSON for APIs, gob for Go-to-Go, binary for performance
- Set limits - Use
Decoder.DisallowUnknownFields()for strict JSON - Consider memory - Stream processing for large files
Common Use Cases
- Web APIs: JSON for request/response bodies
- Configuration: JSON, XML, or TOML for config files
- Data export: CSV for spreadsheet compatibility
- Binary protocols: Custom binary formats with encoding/binary
- Encryption: Base64 for encoding encrypted data
- Certificates: PEM encoding for SSL/TLS certificates