Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

http - 为什么在http.HandleFunc的回调中使用指针(Why are pointers used in the callback of http.HandleFunc)

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.

(我遇到了http.HandleFunc函数,可以向其提供回调以处理配置给它的Web请求。)

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
", r.URL.Path)
}

Why is the *http.Request in the handler method a pointer?

(为什么handler方法中的* http.Request是指针?)

.

(。)

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.

(但是我想知道为什么他们要使用指针而不是常规值。)

  ask by Alan Lal translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(也有很好的解释来解释struct和interface之间的区别。)

In Go HTTP handlers, why is the ResponseWriter a value but the Request a pointer?

(在Go HTTP处理程序中,为什么ResponseWriter是一个值,而Request是一个指针?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...