net/http — Built-in HTTP Server
Go's standard library includes a production-ready HTTP server. No framework needed for simple APIs:
package main
import (
"encoding/json"
"net/http"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func handleUsers(w http.ResponseWriter, r *http.Request) {
users := []User{{1, "Alice"}, {2, "Bob"}}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
func main() {
http.HandleFunc("/api/users", handleUsers)
http.ListenAndServe(":8080", nil)
}
Gin Framework
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(200, gin.H{"id": id, "name": "Alice"})
})
r.POST("/users", func(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
c.JSON(201, user)
})
r.Run(":8080")
}
Key Takeaway: Use
net/http for simple APIs. Use Gin for REST APIs with routing, validation, and middleware. Use Chi for a lightweight router that stays close to net/http.HTTP Request Flow in Go
Client
HTTP request
→
Router
match path
→
Middleware
auth, logging
→
Handler
business logic
→
Response
JSON/HTML
Practice Exercises
Hard Production Scenario
Design a solution using these concepts for a real-world production system.
Hard Performance Analysis
Benchmark two different approaches and explain which is better and why.