The net/http package in Go is a fundamental part of the language's standard library, providing tools for building both HTTP servers and clients. Whether you're creating a web application or interacting with external APIs, understanding how to use this package is essential.
In this tutorial, we'll explore how to build basic HTTP servers and clients using the net/http package. We'll cover everything from setting up a server to handling requests and responses, as well as making HTTP requests to other services.
To create an HTTP server in Go, you need to import the net/http package and define a handler function that will process incoming requests. The http.HandleFunc function is used to associate URLs with handler functions.
Here's a simple example of how to set up an HTTP server:
1package main23import (4"fmt"5"log"6"net/http"7)89func helloHandler(w http.ResponseWriter, r *http.Request) {10fmt.Fprintf(w, "Hello, World!")11}1213func main() {14http.HandleFunc("/", helloHandler)15log.Println("Starting server at port 8080")16if err := http.ListenAndServe(":8080", nil); err != nil {17log.Fatal(err)18}19}
In this example:
helloHandler function that writes "Hello, World!" to the response.http.HandleFunc to map the root URL ("/") to our handler function.http.ListenAndServe.The http.ResponseWriter interface is used to send responses back to the client. The *http.Request struct contains information about the incoming request, such as the URL, headers, and body.
Here's an example of how to handle different HTTP methods:
1package main23import (4"fmt"5"log"6"net/http"7)89func methodHandler(w http.ResponseWriter, r *http.Request) {10switch r.Method {11case "GET":12fmt.Fprintf(w, "Received a GET request")13case "POST":14fmt.Fprintf(w, "Received a POST request")15default:16http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)17}18}1920func main() {21http.HandleFunc("/", methodHandler)22log.Println("Starting server at port 8080")23if err := http.ListenAndServe(":8080", nil); err != nil {24log.Fatal(err)25}26}
In this example:
methodHandler function that checks the HTTP method of the request.To make HTTP requests in Go, you can use the http.Client struct. This allows you to send GET, POST, and other types of requests to external services.
Here's an example of how to make a GET request:
1package main23import (4"fmt"5"io/ioutil"6"log"7"net/http"8)910func fetchExample() {11resp, err := http.Get("https://example.com")12if err != nil {13log.Fatal(err)14}15defer resp.Body.Close()1617body, err := ioutil.ReadAll(resp.Body)18if err != nil {19log.Fatal(err)20}2122fmt.Println(string(body))23}2425func main() {26fetchExample()27}
In this example:
http.Get to make a GET request to "https://example.com".ioutil.ReadAll.Let's create a simple HTTP server that responds with different messages based on the URL path:
1package main23import (4"fmt"5"log"6"net/http"7)89func homeHandler(w http.ResponseWriter, r *http.Request) {10fmt.Fprintf(w, "Welcome to the homepage!")11}1213func aboutHandler(w http.ResponseWriter, r *http.Request) {14fmt.Fprintf(w, "About us page")15}1617func main() {18http.HandleFunc("/", homeHandler)19http.HandleFunc("/about", aboutHandler)20log.Println("Starting server at port 8080")21if err := http.ListenAndServe(":8080", nil); err != nil {22log.Fatal(err)23}24}
In this example:
homeHandler and aboutHandler."/") to homeHandler and /about to aboutHandler.Let's create an HTTP client that sends a POST request with some JSON data:
1package main23import (4"bytes"5"encoding/json"6"fmt"7"io/ioutil"8"log"9"net/http"10)1112type Payload struct {13Name string `json:"name"`14Email string `json:"email"`15}1617func postExample() {18payload := Payload{19Name: "John Doe",20Email: "john.doe@example.com",21}2223jsonPayload, err := json.Marshal(payload)24if err != nil {25log.Fatal(err)26}2728req, err := http.NewRequest("POST", "https://example.com/api/users", bytes.NewBuffer(jsonPayload))29if err != nil {30log.Fatal(err)31}32req.Header.Set("Content-Type", "application/json")3334client := &http.Client{}35resp, err := client.Do(req)36if err != nil {37log.Fatal(err)38}39defer resp.Body.Close()4041body, err := ioutil.ReadAll(resp.Body)42if err != nil {43log.Fatal(err)44}4546fmt.Println(string(body))47}4849func main() {50postExample()51}
In this example:
Payload struct to represent the JSON data.Content-Type header to application/json.http.Client and print the response body.In the next section, we'll explore the encoding/json package, which is essential for working with JSON data in Go. This will be particularly useful when interacting with APIs or handling JSON responses from HTTP requests.
Stay tuned!