-1

I'm trying to learn go for web programming. I came across the http.HandleFunc function , to which i could provide a callback to handle the web request configured to it.

My small program looks like the following.

package main

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

var count int
var mu sync.Mutex

func main() {
    var p Point
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "URL.Path =:%q\n", r.URL.Path)
}

Why is the *http.Request in the handler method a pointer? . I understand that this is how the designed it. But I would like to know why they are mandating a pointer instead of a regular value.

Alan Lal
  • 147
  • 2
  • 8

2 Answers2

0

Since pointer only contains reference, we can use it instead of making a new copy of the request. This way everyone who is working on request struct can see the changes.

There is also good explanation explaining difference between struct and interface. In Go HTTP handlers, why is the ResponseWriter a value but the Request a pointer?

Umar Hussain
  • 3,461
  • 1
  • 16
  • 38
0

From the docs a http.Request is a quite large & complex struct: https://golang.org/pkg/net/http/#Request

So for efficiency, a pointer is better than copy-by-value non-pointer.

Also passing a pointer allows any modifications to the struct to persist e.g. ParseForm.

colm.anseo
  • 19,337
  • 4
  • 43
  • 52