Building Microservices with Golang. Part 3: Creating the User Service

In this section, we will focus on creating the user service, one of the microservices in our application. We will set up the project structure, define the necessary files and directories, and lay the foundation for building the user service.

Step 1: Project Structure: Create a new directory for your user service project. Inside this directory, create the following subdirectories:

user-service/
    ├── cmd/
    ├── pkg/
    └── api/

You can use the following command to create project structure

mkdir -p user-service/{cmd,pkg,api}

The cmd directory will contain the main package and entry point for the user service. The pkg directory is where you will store reusable packages or modules. The api directory will hold the files responsible for handling the HTTP endpoints and business logic specific to the user service.

Step 2: Initialize Go Modules: Navigate to the root of the user service directory in your terminal or command prompt. Initialize Go modules by executing the following command:

go mod init github.com/your-username/user-service

Replace github.com/your-username/user-service with the actual URL or path you want to use for your project’s module.

Step 3: Implement the User Service Entry Point: Inside the cmd directory, create a new file named main.go. This file will serve as the entry point for our user service. Open main.go in a text editor and add the following code:

package main

import (
	"log"
	"net/http"
)

func main() {
	// Start the user service
	log.Println("Starting User Service...")

	// TODO: Add service initialization and configuration code here

	// Start the HTTP server
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("Failed to start the server: ", err)
	}
}

This code sets up a basic HTTP server and defines the entry point for our user service. We will add the service initialization and configuration code later.

Step 4: Create API Handlers: Inside the api directory, create a new file named handlers.go. This file will contain the HTTP request handlers for the user service’s API endpoints. Open handlers.go in a text editor and add the following code:

package api

import (
	"fmt"
	"net/http"
)

// HandleGetUser handles the GET request for retrieving a user by ID
func HandleGetUser(w http.ResponseWriter, r *http.Request) {
	// TODO: Add code to handle the GET request for retrieving a user
	// Extract the user ID from the request and fetch the user from the database

	// Example response
	userID := r.URL.Query().Get("id")
	response := fmt.Sprintf("User ID: %s", userID)

	// Write the response
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(response))
}

// HandleCreateUser handles the POST request for creating a new user
func HandleCreateUser(w http.ResponseWriter, r *http.Request) {
	// TODO: Add code to handle the POST request for creating a new user
	// Extract user data from the request and create a new user in the database

	// Example response
	response := "User created successfully"

	// Write the response
	w.WriteHeader(http.StatusCreated)
	w.Write([]byte(response))
}

These handler functions will be responsible for handling the GET and POST requests for retrieving and creating users, respectively. Implement the necessary functionality for interacting with the database or any other data storage mechanism you choose to use.

Step 5: Wire Up API Endpoints: Inside the main.go file, import the api package and register the API endpoints. Add the following code snippet at the appropriate place in the main function:

// Import the api package
import (
	"github.com/your-username/user-service/api"
)

// ...

func main() {
	// ...

	// Register API endpoints
	http.HandleFunc("/users", api.HandleGetUser).Methods("GET")
	http.HandleFunc("/users", api.HandleCreateUser).Methods("POST")

	// ...
}

This code registers the HandleGetUser function for the GET /users endpoint and the HandleCreateUser function for the POST /users endpoint.

In this section, we created the user service project structure, initialized Go modules, and set up the entry point for our user service. We also defined the API handlers for the user service’s GET and POST endpoints. In the next section, we will dive into implementing the functionality of the user service, including interacting with a database or data storage mechanism.

Leave a Reply

Your email address will not be published. Required fields are marked *