Table of Contents
- Introduction
- Prerequisites
- Setting Up Go
- Creating the Ad Serving Microservice
- Handling Concurrent Requests
- Testing the Microservice
- Conclusion
Introduction
In this tutorial, we will guide you through the process of building a Go-based microservice for ad serving. By the end of this tutorial, you will have a basic understanding of building a microservice with Go, handling concurrent requests, and testing the microservice.
Prerequisites
Before starting this tutorial, you should have the following:
- Basic knowledge of Go programming language
- Go installed on your machine
- A text editor or integrated development environment (IDE) for writing Go code
Setting Up Go
First, let’s ensure that Go is installed on your machine by following these steps:
- Visit the official Go website at https://golang.org/dl/
- Download the appropriate installer for your operating system (Windows, macOS, or Linux)
- Run the installer and follow the installation prompts
-
Open a new terminal or command prompt window
-
Verify that Go is installed correctly by running the following command:
go version
If Go is installed correctly, you should see the version number printed to the terminal.
Creating the Ad Serving Microservice
Now that we have Go installed, let’s create the ad serving microservice. We will use the Go standard library’s net/http
package to handle HTTP requests and responses.
-
Create a new directory for your project:
mkdir ad-serving-microservice cd ad-serving-microservice
-
Initialize a new Go module:
go mod init github.com/your-username/ad-serving-microservice
-
Create a new file named
main.go
and open it in your text editor or IDE. -
Add the following code to
main.go
:package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/ads", handleAdsRequest) log.Fatal(http.ListenAndServe(":8080", nil)) } func handleAdsRequest(w http.ResponseWriter, r *http.Request) { // Generate and return a sample ad ad := "Buy our product!" fmt.Fprint(w, ad) }
In the code above, we define a
handleAdsRequest
function to handle requests to the “/ads” endpoint. Inside this function, we generate a sample ad and write it as the response.The
main
function binds thehandleAdsRequest
function to the “/ads” endpoint and starts the HTTP server on port 8080. -
Save the
main.go
file and exit your text editor or IDE. -
Build and run the microservice:
go build ./ad-serving-microservice
You should see the microservice start and listen for incoming requests on port 8080.
Handling Concurrent Requests
To make our ad serving microservice handle concurrent requests efficiently, we can leverage Go’s goroutines and channels. Let’s update our handleAdsRequest
function to use goroutines.
-
Update the
handleAdsRequest
function as follows:func handleAdsRequest(w http.ResponseWriter, r *http.Request) { // Create an unbuffered channel to receive the ad adChan := make(chan string) // Start a goroutine to generate the ad go generateAd(adChan) // Receive the ad from the channel ad := <-adChan // Write the ad as the response fmt.Fprint(w, ad) } func generateAd(adChan chan<- string) { // Generate the ad ad := "Buy our amazing product!" // Send the ad to the channel adChan <- ad }
In the updated code, we create an unbuffered channel
adChan
to receive the ad from thegenerateAd
goroutine. We start thegenerateAd
goroutine, which generates the ad and sends it to theadChan
channel. Finally, we receive the ad from theadChan
channel and write it as the HTTP response. -
Save the
main.go
file and restart the microservice:go build ./ad-serving-microservice
Now our microservice can handle multiple concurrent requests efficiently.
Testing the Microservice
We can use Go’s built-in testing framework to test our ad serving microservice. Let’s create a test file named main_test.go
and write some test cases.
-
Create a new file named
main_test.go
and open it in your text editor or IDE. -
Add the following code to
main_test.go
:package main import ( "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestHandleAdsRequest(t *testing.T) { req, err := http.NewRequest("GET", "/ads", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(handleAdsRequest) handler.ServeHTTP(rr, req) resp := rr.Result() body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatal(err) } expected := "Buy our amazing product!" if string(body) != expected { t.Errorf("Expected %q, but got %q", expected, string(body)) } }
In the code above, we write a test case to verify that the
/ads
endpoint returns the expected ad. -
Save the
main_test.go
file and exit your text editor or IDE. -
Run the tests:
go test
The tests should pass, indicating that our microservice is functioning correctly.
Conclusion
In this tutorial, we learned how to build a Go-based microservice for ad serving. We covered the basics of setting up Go, creating an HTTP server, handling concurrent requests using goroutines, and testing the microservice. You can now extend this microservice to connect with a database, implement additional features, and handle more complex ad serving scenarios. Happy coding!