This guide demonstrates how to build a series of RESTful APIs using the Echo web framework in Go. We cover:
- Setting up a simple Echo web server.
- Creating a server with dynamic URL parameters.
- Implementing a user registration API with validation.
- Go (version 1.16 or higher recommended)
- A code editor (e.g., VS Code)
- Postman or a similar tool for testing APIs
- Internet connection to download dependencies
This example demonstrates how to set up a basic web server using the Echo framework in Go. The server listens on port 1212
and serves a simple GET
endpoint that returns a "Hello!" response.
-
Create a new directory for the project:
mkdir echo-web-server cd echo-web-server
-
Initialize the project and install Echo:
go mod init echo-web-server go get github.com/labstack/echo/v4
-
Create a file named
main.go
and paste the following code:package main import ( "net/http" "github.com/labstack/echo/v4" ) func main() { // Create Echo instance e := echo.New() // Root endpoint // We define a GET endpoint. // This determines the function that will be run when someone sends a GET request to http://localhost:8080. e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "Hello!") // We send a text (string) response. }) // Start the server and listen on port 1212 e.Logger.Fatal(e.Start(":1212")) }
-
Clean up dependencies
go mod tidy
-
Run the Server with:
go run main.go
-
The server will start listening on port 1212. Open your browser or use a tool like Postman to make a GET request to:
http://localhost:1212/
-
You should see the response:
Hello!
This example demonstrates how to use dynamic URL parameters to personalize responses.
Update the main.go
file with the following code:
package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
func main() {
// Create Echo instance
e := echo.New()
// Root endpoint
// We define a GET endpoint with a dynamic URL parameter.
// This determines the function that will be run when someone sends a GET request to http://localhost:1212/<name>.
e.GET("/:name", func(c echo.Context) error {
name := c.Param("name") // Extract the value from the URL parameter.
return c.String(http.StatusOK, "Hello!, "+name+"!") // Send a response with the extracted name.
})
// Start the server and listen on port 1212
e.Logger.Fatal(e.Start(":1212"))
}
-
Start the server:
go run main.go
-
Open your browser or Postman and navigate to:
http://localhost:1212/YourName
-
Replace
YourName
with any name to receive a personalized greeting.
This example is a simple Go-based REST API for user registration. It accepts user details, validates the input, and returns a response.
- POST
/register
endpoint for user registration. - Validates the incoming JSON request:
- Ensures
name
,email
, andpassword
fields are provided. - Checks if the
email
is in a valid format.
- Ensures
- Returns appropriate error responses for invalid input.
- Logs requests using middleware.
Update the main.go
file with the following code:
package main
import (
"net/http"
"regexp"
// https://pkg.go.dev/regexp
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
// https://pkg.go.dev/github.com/labstack/echo/v4/middleware
)
// Defining the User Struct
type User struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required"`
}
func main() {
// Echo instance
e := echo.New()
// Middleware to log requests
e.Use(middleware.Logger())
// Register endpoint
e.POST("/register", func(c echo.Context) error {
// Initialize a User struct to bind incoming data
var user User // Creates a variable user of type User
// Bind JSON body to the struct
if err := c.Bind(&user); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
"error": "Invalid request",
})
}
// Validate email format
if !isValidEmail(user.Email) {
return c.JSON(http.StatusUnprocessableEntity, map[string]string{
"error": "Invalid email format",
})
}
// Return success response
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "User registered successfully",
"user": map[string]string{
"name": user.Name,
"email": user.Email,
},
})
})
// Start the server and listen on port 1212
e.Logger.Fatal(e.Start(":1212"))
}
// Email validation function
func isValidEmail(email string) bool {
// Basic email regex
regex := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
re := regexp.MustCompile(regex)
return re.MatchString(email)
}
-
Start the server:
go run main.go
-
Use Postman to send a
POST
request to:http://localhost:1212/register
-
Example request body:
{ "name": "Melisa Acar", "email": "[email protected]", "password": "secret" }
-
Responses:
- Success (200 OK):
{ "message": "User registered successfully", "user": { "name": "Melisa Acar", "email": "[email protected]" } }
- Invalid Email (422 Unprocessable Entity):
{ "error": "Invalid email format" }
- Invalid Request (400 Bad Request):
{ "error": "Invalid request" }
- Open Postman and create a new
POST
request. - Set the URL to:
http://localhost:1212/register
. - Go to the Body tab, select
raw
, and set the format toJSON
. - Enter the request body given above.
- Click Send.
- Unused Imports and Variables: Go does not allow unused imports or variables. Tools like
gofmt
andgoimports
help maintain code standards. - Dependency Management: Use
go mod tidy
to clean up dependencies.