Go Essentials

Go Essentials

Go Essentials

Building an HTTP Server in Go

Building an HTTP Server in Go

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:

  1. Run the server:

    go run main.go
    

    Untitled (13).png

  2. 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>
    
  3. Get all users:

    curl <http://localhost:8080/users>
    

You should see the list of users, including the newly registered user:

Untitled (12).png

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!

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board