Go HTTP package fundamentals¶
The net/http package is a standard library in Go that provides HTTP client and server implementations^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. It is a core component for building web distributed systems, microservices, and APIs^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Server implementation¶
Go simplifies the creation of an HTTP server through the http.ListenAndServe function^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. This function starts a server that listens on a specified network address (e.g., :8080).
The standard pattern for invoking the server is to pass a network address and a handler^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]:
http.ListenAndServe(":8080", nil)
When nil is passed as the second argument (the handler), Go utilizes the DefaultServeMux^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. The DefaultServeMux is a default request multiplexer that handles the routing of incoming HTTP requests to the appropriate handler functions.
Routing and Handlers¶
To respond to specific requests, developers register handler functions using http.HandleFunc^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. This function takes two arguments: a route pattern (string) and a function to execute when that route is matched^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Handler Signature¶
Every handler function registered via HandleFunc must adhere to a specific signature^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]:
func handlerName(w http.ResponseWriter, r *http.Request) {
// Logic here
}
http.ResponseWriter: This interface is used to construct the HTTP response. It allows the server to write data back to the client, set status codes, and add headers^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].*http.Request: This structure contains all information regarding the incoming request, including the URL, headers, and body^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Request Handling¶
Accessing Headers¶
The *http.Request object provides access to the request headers via the Header field^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. This field acts as a map (dictionary) where keys are strings and values are slices of strings. You can iterate over headers using a for loop and the range keyword^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Reading the Request Body¶
For methods like POST, the data payload is located in the Body field of the request object^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. Since the body is an io.ReadCloser stream, it is typically read using the ioutil.ReadAll function (in older Go versions) or io.Read utilities to obtain the raw bytes^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Response Handling¶
Writing Data¶
To send data back to the client, the Write method on the ResponseWriter interface is used^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. This method accepts a slice of bytes ([]byte). To send a string, it must be converted to bytes, for example, []byte("response text")^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Setting Headers¶
Headers can be added to the response using the Header() method on the writer, followed by the Add method^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
w.Header().Add("Key", "Value")
Status Codes¶
Servers communicate the outcome of a request using HTTP status codes. The WriteHeader method on the ResponseWriter is used to explicitly set the status code (e.g., 200, 404, 405, 500)^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
JSON Handling¶
Building APIs often involves sending and receiving [[JSON]] data.
* Sending: Structs or slices are converted to JSON using json.Marshal, and the resulting bytes are written to the ResponseWriter^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
* Receiving: The incoming request body is read into bytes, and json.Unmarshal is used to convert that data into Go structs^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]. This process allows for data validation; if unmarshalling fails, the server can return a 400 Bad Request status^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
HTTP methods¶
The http package supports various standard HTTP methods, including GET and POST^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
- GET: Typically used to retrieve data^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
- POST: Typically used to create or update resources^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Developers can check the specific method used by accessing r.Method inside their handler to enforce logic, such as preventing GET requests on an update endpoint or returning a 405 Method Not Allowed status if the method is unsupported^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].
Sources¶
^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]