The ‘net/http‘ package in Go provides an extensive and efficient HTTP client and server implementation to build and manipulate HTTP and HTTPS protocols. The package is very powerful, yet it maintains an easy-to-understand API. Here’s a detailed explanation of how it works, with examples.
1. **HTTP Server**
A simple HTTP server can be created in Go with the ‘net/http‘ package. The ‘http.ListenAndServe‘ function listens on a given address and port, and serves incoming requests using the provided handler:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, you've requested: %sn", r.URL.Path)
})
http.ListenAndServe(":8080", nil)
}
In the above example, the ‘http.HandleFunc‘ function maps a function to a specified route, defining how the server should handle the incoming request. The ‘http.ResponseWriter‘ and ‘*http.Request‘ are interfaces provided by the ‘net/http‘ package to interact with the HTTP response and request.
2. **HTTP Client**
The ‘net/http‘ package provides the ‘http.Client‘ type for making HTTP requests. The client’s ‘Get‘, ‘Post‘, and ‘Do‘ methods allow you to make HTTP GET, POST, and custom requests, respectively. Here’s an example of making a simple HTTP GET request using the ‘http.Get‘ method:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
response, err := http.Get("https://example.com")
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
}
In the example, the ‘http.Get‘ function sends a GET request to the specified URL and returns an ‘*http.Response‘ containing the server’s response. The response body is read and printed.
3. **Custom Handlers**
Sometimes, you might need more control over the server’s behavior or need to use middleware. In this case, you can create custom handler functions that implement the ‘http.Handler‘ interface, which consists of a single method, ‘ServeHTTP(w http.ResponseWriter, r *http.Request)‘.
Here’s an example of creating a custom handler:
type CustomHandler struct {
message string
}
func (handler CustomHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, handler.message)
}
func main() {
handler := CustomHandler{message: "Hello from CustomHandler"}
http.Handle("/", handler)
http.ListenAndServe(":8080", nil)
}
In this example, the ‘CustomHandler‘ struct holds a message string. The ‘ServeHTTP‘ method writes this message as a response. The ‘http.Handle‘ function maps the custom handler to the root route.
The Go ‘net/http‘ package offers a comprehensive solution for creating and interacting with HTTP servers and clients. Its ease of use, extensive feature set, and performance make it a popular choice for developers working with HTTP in Go.