- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 388字
- 2021-06-24 17:04:25
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:
- 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.
- 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.
- 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.
- 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.
- Python數據可視化:基于Bokeh的可視化繪圖
- HTML5 Mobile Development Cookbook
- Koa開發:入門、進階與實戰
- Banana Pi Cookbook
- 深入淺出RxJS
- TradeStation交易應用實踐:量化方法構建贏家策略(原書第2版)
- C#實踐教程(第2版)
- Python深度學習:模型、方法與實現
- ElasticSearch Cookbook(Second Edition)
- Visual Foxpro 9.0數據庫程序設計教程
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- Hands-On Full Stack Development with Spring Boot 2.0 and React
- Instant Debian:Build a Web Server
- Vue.js光速入門及企業項目開發實戰
- jQuery Mobile Web Development Essentials(Second Edition)