"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does the `http.Request` Argument Need to Be a Pointer in Go?

Why Does the `http.Request` Argument Need to Be a Pointer in Go?

Published on 2024-11-14
Browse:831

Why Does the `http.Request` Argument Need to Be a Pointer in Go?

Why Must the HTTP Request Argument Be a Pointer?

In Go, the http.Request type is a large struct containing various information about an HTTP request. To handle HTTP requests efficiently, Go uses pointers to avoid the overhead of copying large data structures.

package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hello world"))
    })
    http.ListenAndServe(":8000", nil)
}

If you remove the asterisk (*) in *http.Request, you will encounter an error because the func literal expects a pointer to the http.Request type.

  

github.com/creating_web_app_go/main.go:8: cannot use func literal (type func(http.ResponseWriter, http.Request)) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc

Pointers are used in Go to pass references to objects, rather than copies of the objects themselves. This is more efficient, especially for large structures like http.Request. In addition, http.Request contains state information, such as the HTTP headers and request body, which would be confusing if copied.

Therefore, the http.Request argument must be a pointer to ensure efficient handling of HTTP requests and to maintain the integrity of the state information it contains.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3