Echo Status Codes
When building web applications or APIs with the Echo framework, understanding how to properly set and handle HTTP status codes is crucial for creating robust and user-friendly interfaces. This guide will walk you through everything you need to know about Echo status codes.
Introduction to HTTP Status Codes
HTTP status codes are standardized codes returned by web servers in response to client requests. They indicate whether a specific HTTP request has been successfully completed, needs further action, or has encountered an error.
In the Echo framework, status codes follow the standard HTTP protocol categorization:
- 1xx (Informational): Request received, continuing process
- 2xx (Success): Request successfully received, understood, and accepted
- 3xx (Redirection): Further action needed to complete the request
- 4xx (Client Error): Request contains bad syntax or cannot be fulfilled
- 5xx (Server Error): Server failed to fulfill a valid request
Setting Status Codes in Echo
Echo makes it easy to set status codes in your responses. Here's how you can do it:
Basic Status Code Setting
The simplest way to set a status code is to use the c.JSON()
, c.String()
, or similar response methods:
func helloHandler(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}
In this example, http.StatusOK
represents the status code 200, indicating a successful request.
Common Status Codes in Echo
Here are some common status codes you'll use in Echo applications:
// Success responses
c.JSON(http.StatusOK, response) // 200 - General success
c.JSON(http.StatusCreated, response) // 201 - Resource created
c.NoContent(http.StatusNoContent) // 204 - Success with no content to return
// Client error responses
c.JSON(http.StatusBadRequest, errorMsg) // 400 - Bad request
c.JSON(http.StatusUnauthorized, errorMsg) // 401 - Unauthorized
c.JSON(http.StatusForbidden, errorMsg) // 403 - Forbidden
c.JSON(http.StatusNotFound, errorMsg) // 404 - Resource not found
// Server error responses
c.JSON(http.StatusInternalServerError, errorMsg) // 500 - Server error
Creating Custom Error Responses
For a more consistent error handling approach, you can create custom error responses:
type ErrorResponse struct {
Status int `json:"status"`
Message string `json:"message"`
}
func handleUserNotFound(c echo.Context) error {
errorResponse := ErrorResponse{
Status: http.StatusNotFound,
Message: "User not found",
}
return c.JSON(http.StatusNotFound, errorResponse)
}
Practical Examples
Let's look at some practical examples of handling different scenarios with appropriate status codes.
Example 1: User Registration API
func registerUser(c echo.Context) error {
// Parse user data from request
u := new(User)
if err := c.Bind(u); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
"error": "Invalid user data format",
})
}
// Validate required fields
if u.Username == "" || u.Email == "" {
return c.JSON(http.StatusBadRequest, map[string]string{
"error": "Username and email are required",
})
}
// Check if user already exists
if userExists(u.Email) {
return c.JSON(http.StatusConflict, map[string]string{
"error": "User with this email already exists",
})
}
// Create the user (simplified)
err := createUser(u)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": "Failed to create user",
})
}
// Return success with created user
return c.JSON(http.StatusCreated, u)
}
Example 2: Resource Retrieval with Proper Error Handling
func getArticle(c echo.Context) error {
// Get ID from request
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
"error": "Invalid article ID",
})
}
// Get the article
article, err := findArticleByID(id)
// Handle different error types with appropriate status codes
if err != nil {
if err == ErrArticleNotFound {
return c.JSON(http.StatusNotFound, map[string]string{
"error": "Article not found",
})
}
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": "Failed to retrieve article",
})
}
return c.JSON(http.StatusOK, article)
}
HTTP Status Codes and RESTful API Design
When building RESTful APIs with Echo, using the correct status codes is particularly important:
HTTP Method | Success Status Code | Common Usage |
---|---|---|
GET | 200 (OK) | Retrieve a resource |
POST | 201 (Created) | Create a new resource |
PUT | 200 (OK) | Update a resource (full update) |
PATCH | 200 (OK) | Update a resource (partial update) |
DELETE | 204 (No Content) | Delete a resource |
Advanced Error Handling with Echo's HTTPError
Echo provides a built-in HTTPError
type for more advanced error handling:
func customErrorHandler(c echo.Context) error {
// Some logic that might cause an error
if someCondition {
return echo.NewHTTPError(http.StatusForbidden, "Permission denied")
}
// Continue with normal processing
return c.JSON(http.StatusOK, "Success")
}
You can also create a custom HTTP error handler for your Echo application:
e := echo.New()
e.HTTPErrorHandler = func(err error, c echo.Context) {
code := http.StatusInternalServerError
message := "Internal Server Error"
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
message = he.Message.(string)
}
// You could also log the error here
c.JSON(code, map[string]string{
"error": message,
})
}
Best Practices for Status Codes
- Be specific: Use the most appropriate status code for each situation
- Be consistent: Maintain consistent status codes across your API
- Include error details: Provide meaningful error messages with error status codes
- Log server errors: Always log 5xx errors for debugging
- Don't expose sensitive information: Sanitize error messages sent to clients
- Consider versioning: Include API version in error responses for better debugging
Summary
Understanding and correctly implementing HTTP status codes in your Echo applications is essential for building robust, user-friendly APIs and web services. Status codes provide important information to clients about the result of their requests, helping both humans and machines understand what happened and what to do next.
By following the examples and best practices outlined in this guide, you'll be well on your way to creating Echo applications with proper status code handling.
Additional Resources
Exercises
- Create a simple Echo API with endpoints that return different status codes based on input parameters.
- Implement a custom error handler for your Echo application that formats all error responses consistently.
- Build a RESTful API for a resource (like books or users) with proper status codes for all operations (GET, POST, PUT, DELETE).
- Add middleware that logs all non-200 responses for debugging purposes.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)