Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdfNabajyoti Banik
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...Third Rock Techkno
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...AndreeaTom
Ad
Structs to JSON: How Go Powers REST APIs
1. Structs to JSON: How Go Powers
REST APIs
A comprehensive exploration of Go's powerful struct-to-JSON
capabilities for building robust RESTful services
by Emily Achieng
DevOps & Software Engineer
2. Agenda
Foundations
Go structs fundamentals, JSON as API language
Implementation
Struct tags for JSON, Encoding/Decoding, Data validation
Real-world Application
Database integration, API endpoints, Service flow
3. Go Structs: Building Blocks of Data
Go structs are collections of fields with typed data that:
Custom types
Grouping data
Object-oriented patterns
Type safety
Think of structs as blueprints for your data.
4. Example: Go Struct Definition
Here’s a typical Go struct used for user data in REST APIs:
type User struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
}
5. Structs to JSON: The Transformation
JSON is the standard for data exchange in web APIs.
Go's encoding/json package makes it simple to convert between Go
structs and JSON.
The main function for this is json.Marshal, which turns a Go struct
into its JSON text representation.
6. Example: Struct to JSON Conversion
Here’s how you convert a Go struct to JSON using json.Marshal :
import "encoding/json"
type Product struct {
Name string
Price float64
}
p := Product{Name: "Laptop", Price: 1200.50}
jsonData, _ := json.Marshal(p)
// Output: {"Name":"Laptop","Price":1200.5}
7. Structs to JSON: The Transformation
1. Go Structs
Strongly typed data structures with fields and methods
2. Struct Tags
Metadata for controlling serialization behavior
3. Encoding/Decoding
json.Marshal() and json.Unmarshal() functions
4. JSON Response
Client-consumable data format
8. Struct Tags: The Secret Sauce
Struct tags are string literals that attach metadata to fields:
type User struct {
ID int `db:"id" json:"id"`
Username string `db:"username" json:"username"`
Email string `db:"email" json:"email"`
Active bool `db:"active" json:"active"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
9. Common JSON Tag Options
1. json:"name"
Rename field (change the JSON key name for this field)
2. json:"name,omitempty"
Skip empty values (omit the field from JSON if it is empty)
These options help you control how your struct fields are
represented in JSON, making your API responses cleaner and more
flexible.
10. Common JSON Tag Options (cont.)
3. json:"-"
Exclude from JSON (do not include this field in the output)
4. json:",string"
Force string encoding (convert the field to a JSON string)
The json:"fieldname" tag controls how the field appears in JSON
output.
11. Request, Process, Decode, Encode
Request
HTTP request arrives with JSON payload
{ "username": "gopher", "email": "[email protected]", "active":
true }
Process Data
Perform operations, such as validation and database storage, using
the typed Go struct
if err := user.Validate(); err != nil { // Handle validation
error }
createdUser, err := store.CreateUser(user)
12. Request, Process, Decode, Encode (cont.)
Decode
Parse JSON into struct
var user model.User
json.NewDecoder(r.Body).Decode(&user)
Encode
Convert struct back to JSON
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(createdUser)
13. Validation: Ensuring Data Integrity
What is Validation?
Ensures user data follows business rules before processing.
Why is Validation Important?
Catches bad data early and keeps the application reliable.
How Does Validation Work?
Define rules (e.g., username length, email format)
Return clear error messages if validation fails
15. Database Integration: Example Code
type User struct { ID int; Name string }
user := User{}
db.QueryRow("SELECT * FROM users WHERE id = ?", id).Scan(&user.ID, &user.Name)
json, _ := json.Marshal(user)
w.Write(json)
Use struct tags to map fields to database columns.
16. Putting It All Together
Define Data Models
Create structs with appropriate JSON and DB tags
Implement Storage Layer
Database operations that convert between structs and DB rows
17. Putting It All Together (cont.)
Build HTTP Handlers
Process requests and encode/decode JSON
Register Routes
Connect HTTP endpoints to handlers
Go's struct system provides a seamless pipeline from HTTP request
to database and back, with type safety at every step.
18. Error Handling: Consistent API Responses
Robust APIs
Provide clear, consistent error messages to clients. Go allows
defining custom error structs that can be marshaled directly into
JSON.
Standardize Errors
Return predictable JSON formats for all error types.
type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}
19. Key Takeaways
Go structs are your data foundation
Model complex, reliable API data.
Struct tags give you control
Customize JSON serialization easily.
Clean architecture matters
Separate layers for maintainable, scalable APIs.
Validation & error handling ensure reliability
Catch bad data and provide clear feedback.