Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Hands-On RESTful Web Services with Go

You're reading from   Hands-On RESTful Web Services with Go Develop elegant RESTful APIs with Golang for microservices and the cloud

Arrow left icon
Product type Paperback
Published in Feb 2020
Publisher Packt
ISBN-13 9781838643577
Length 404 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Naren Yellavula Naren Yellavula
Author Profile Icon Naren Yellavula
Naren Yellavula
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Getting Started with REST API Development 2. Handling Routing for our REST Services FREE CHAPTER 3. Working with Middleware and RPC 4. Simplifying RESTful Services with Popular Go Frameworks 5. Working with MongoDB and Go to Create a REST API 6. Working with Protocol Buffers and gRPC 7. Working with PostgreSQL, JSON, and Go 8. Building a REST API Client in Go 9. Asynchronous API Design 10. GraphQL and Go 11. Scaling our REST API Using Microservices 12. Containerizing REST Services for Deployment 13. Deploying REST Services on Amazon Web Services 14. Handling Authentication for our REST Services 15. Other Books You May Enjoy

Understanding Go's net/http package

Accepting HTTP requests is the primary goal of a web server. In Go, there is a system-level package that helps developers create HTTP servers and clients. The name of the package is net/http. We can understand the functionality of the net/http package by creating a small example. The example accepts an incoming request and returns the timestamp of the server. Let us see the steps for creating such a server:

  1. Create the program file as follows:
touch -p $GOPATH/src/github.com/git-user/chapter2/healthCheck/main.go

Now, we have a file where we can develop a server with a Health Check API that returns a date/time string.

  1. Import the net/http package and create a function handler called HealthCheck. The http.HandleFunc is a method that takes a route and a function handler as its arguments. This function handler has to return an http.ResponseWriter object:
package main

import (
"io"
"log"
"net/http"
"time"
)

// HealthCheck API returns date time to client
func HealthCheck(w http.ResponseWriter, req *http.Request) {
currentTime := time.Now()
io.WriteString(w, currentTime.String())
}

func main() {
http.HandleFunc("/health", HealthCheck)
log.Fatal(http.ListenAndServe(":8000", nil))
}

The preceding code creates a HealthCheck function and attaches it to an HTTP route. HandleFunc is used to attach a route pattern to a handler function. ListenAndServe starts a new HTTP server. It returns an error if the server launch is unsuccessful. It takes address:port as the first argument and the second argument is nil, which says use the default multiplexer. We will see multiplexers in detail in the upcoming sections.

Use the log function to debug potential errors. The ListenAndServe function returns an error if there is one.
  1. Now, we can start the web server using this command:
go run $GOPATH/src/github.com/git-user/chapter2/healthCheck/main.go

Run the healthCheck.go file from a shell.

  1. Now, fire up a shell or browser to see the server in action. Here, we use the curl request:
curl -X GET http://localhost:8000/health

The response is as follows:

2019-04-10 17:54:05.450783 +0200 CEST m=+6.612810181

Go has a different concept for handling request and response. We used the io library to write to the response. For web development, we can use a template to automatically fill in the details. Go's internal URL handlers use a ServeMux multiplexer. In the next section, we will discuss more on ServeMux, a built-in URL router in Go.

You have been reading a chapter from
Hands-On RESTful Web Services with Go - Second Edition
Published in: Feb 2020
Publisher: Packt
ISBN-13: 9781838643577
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime