Congratulations on reaching this milestone! Let's apply everything we've learned to build a simple HTTP server using Go. We'll create an HTTP server that handles basic user registration requests. For simplicity, we won't use databases and store the user data in memory.
Let's start by creating the project structure:
user-registration/
|- main.go
|- user.go
|- go.mod
Run these commands to initialize the new repository for Go and add any requirements:
go mod init
go mod tidy
If you check the content of the generated file, you will find something like the following:
go.mod
module user-registration
go 1.19
Now, paste this in the main.go
file:
main.go
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type User struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}
var users = []User{
{
ID: 1,
Username: "john_doe",
Email: "[email protected]",
}, {
ID: 2,
Username: "jane_smith",
Email: "[email protected]",
},
}
func handleUserRegistration(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var newUser User
err := json.NewDecoder(r.Body).Decode(&newUser)
if err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
users = append(users, newUser)
w.WriteHeader(http.StatusCreated)
}
func handleGetAllUsers(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
response, err := json.Marshal(users)
if err != nil {
http.Error(w, "Failed to retrieve users", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
func main() {
http.HandleFunc("/register", handleUserRegistration)
http.HandleFunc("/users", handleGetAllUsers)
fmt.Println("Server started at <http://localhost:8080>")
http.ListenAndServe(":8080", nil)
}
JSON is actually outside the scope of this guide, but please know that it is a data formatting system. Next, we can have a user.go
file to handle all user operations, but we don’t need one for this short demo:
user.go
package main
// You can define additional User-related functions or types here if needed.
Now, let's run the server and test our endpoints using curl
:
Run the server:
go run main.go
Register a new user by opening a new terminal and pasting this shell script:
curl -X POST -d '{"id": 3, "username": "backendcoder", "email": "[email protected]"}' <http://localhost:8080/register>
Get all users:
curl <http://localhost:8080/users>
You should see the list of users, including the newly registered user:
This simple HTTP server demonstrates how to handle HTTP requests for user registration and retrieval using Go. Of course, in a real-world scenario, you would use a database to persist the user data and implement proper error handling and validation. But this project is a great starting point to understand the basics of building backend HTTP servers with Go.
Congratulations on completing this milestone project! Continue exploring Go's features and building more advanced applications to become a proficient Go backend engineer.
Where to go from here
You just learned the basics of Go. If you understand the logic of the milestone project, great! You can scale it by adding features like deleting and modifying user details and storing users in a repository. You can also split the logic into different packages, as we saw in the guide, and add to the logic. You can also Dockerize the application and deploy it with practice. Read our Ultimate Guide to Docker article here.
If you don’t understand the logic in the milestone project, you should engage in research to try to understand everything that happened. Then when you do, you can follow the steps above to scale the project.
Happy coding!