In this tutorial, you will learn how to make HTTP requests using Go’s net/http
package. The strength of this package lies in its versatility and ease of use, making it suitable for both creating HTTP clients and servers. The tutorial will guide you through the process of making various types of HTTP requests, including GET
and POST
, customizing requests with headers, and setting timeouts for requests.
Prerequisites
Before starting this tutorial, ensure that you have the following:
- Go version 1.16 or higher installed on your machine.
- Basic knowledge of how to use Go to create a simple HTTP server.
- Familiarity with goroutines and channels; if you’re new, consider reviewing how to run multiple functions concurrently in Go.
Making a GET Request
To begin, you will create a simple HTTP server that responds to requests. Create a directory for your project and a main.go
file inside it.
The following example shows how to create a basic HTTP server that listens on a specified port and prints a message every time it receives a request.
package mainimport ( "fmt" "net/http" "os")// Port on which the server listensconst serverPort = 3333func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Printf("server: %s /", r.Method) }) server := http.Server{ Addr: fmt.Sprintf(":%d", serverPort), Handler: mux, } go func() { if err := server.ListenAndServe(); err != nil { fmt.Printf("error running http server: %s", err) } }() // Create a URL to the server requestURL := fmt.Sprintf("http://localhost:%d", serverPort) // Making a GET request res, err := http.Get(requestURL) if err != nil { fmt.Printf("error making http request: %s", err) os.Exit(1) } fmt.Printf("client: got response!") fmt.Printf("client: status code: %d", res.StatusCode)}
Sending a POST Request
Next, you will update your program to send a POST request with a JSON body. This involves modifying the handler to print additional information about incoming requests and to read the body of the request.
Update the server handler to include the necessary imports for reading the request body and updating the request to POST.
import ( "bytes" "encoding/json")// Change the HTTP request handling to include body reading, query parameters, etc.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Printf("server: %s /", r.Method) // Reading query parameters fmt.Printf("server: query id: %s", r.URL.Query().Get("id")) // Reading request body reqBody, err := io.ReadAll(r.Body) if err != nil { fmt.Printf("server: could not read request body: %s", err) return } fmt.Printf("server: request body: %s", reqBody) // Sending response w.Write([]byte(`{"message": "hello!"}`))})// To send the POST requestjsonBody := []byte(`{"client_message": "hello, server!"}`)bodyReader := bytes.NewReader(jsonBody)req, err := http.NewRequest(http.MethodPost, requestURL+"?id=1234", bodyReader)if err != nil { fmt.Printf("client: could not create request: %s", err) os.Exit(1)}req.Header.Set("Content-Type", "application/json")client := http.Client{Timeout: 30 * time.Second}res, err := client.Do(req)if err != nil { fmt.Printf("client: error making http request: %s", err) os.Exit(1)}defer res.Body.Close()fmt.Printf("client: got response!")fmt.Printf("client: status code: %d", res.StatusCode)
Customizing an HTTP Request
You need to ensure that your request is accompanied by the correct content type and include a specific timeout. This allows the server to handle JSON data correctly.
The adjustments made in the previous section to set the Content-Type
and create a custom client are essential. This not only helps in accurately describing the type of data sent but also prevents requests from hanging indefinitely by enforcing wait times.
req.Header.Set("Content-Type", "application/json")client := http.Client{Timeout: 30 * time.Second}res, err := client.Do(req)// Check for errors and handle responses as shown earlier
Conclusion
Throughout this tutorial, you’ve created an HTTP server and made various types of requests to it using Go’s net/http
package. You began by making a simple GET request, then enhanced your program to perform a POST request with JSON data, customizing headers along the way. You also learned how to set a timeout for requests using a custom HTTP client.
For further exploration, consider examining the documentation for the net/http
package, which includes additional features such as cookie handling and more complex request management.
Welcome to DediRock, your trusted partner in high-performance hosting solutions. At DediRock, we specialize in providing dedicated servers, VPS hosting, and cloud services tailored to meet the unique needs of businesses and individuals alike. Our mission is to deliver reliable, scalable, and secure hosting solutions that empower our clients to achieve their digital goals. With a commitment to exceptional customer support, cutting-edge technology, and robust infrastructure, DediRock stands out as a leader in the hosting industry. Join us and experience the difference that dedicated service and unwavering reliability can make for your online presence. Launch our website.