How do you handle HTTP requests in Go?

In Go, you can handle HTTP requests using the "net/http" package. Here's a simple example that demonstrates how to handle a GET request:
HTTP requests in Go

Example

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

In this example, we define a handler function that takes two arguments: an http.ResponseWriter and an http.Request. The http.ResponseWriter is used to write the response back to the client, while the http.Request contains information about the incoming request, such as the HTTP method and headers.

We then register our handler function with the HTTP server by calling http.HandleFunc("/", handler). This tells the server to call our handler function whenever a request is made to the root path ("/").

Finally, we start the server by calling http.ListenAndServe(":8080", nil). This tells the server to listen on port 8080 and handle incoming requests. The nil parameter specifies that we're using the default HTTP server, which we can customize if we need to.

This is just a simple example, but the "net/http" package provides many more features for handling HTTP requests, such as routing, middleware, and support for various HTTP methods and headers.


Most Helpful This Week