登录
首页 >  Golang >  Go问答

值和引用

来源:stackoverflow

时间:2024-03-03 13:03:25 307浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《值和引用》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我有点想知道为什么下面的代码可以工作:

var serverStartedTime time.Time // Holds the time since the server is started.

type ServerInformation struct {
    Uptime ServerUptimeInformation `json:"uptime"`
}

type ServerUptimeInformation struct {
    Hours       int64 `json:"hours"`
    Minutes     int64 `json:"minutes"`
    Seconds     int64 `json:"seconds"`
    NanoSeconds int64 `json:"nanoSeconds"`
}

func main() {
    serverStartedTime = time.Now()

    http.HandleFunc("/api/v1/health", getHealthHandler)

    log.Fatal(http.ListenAndServe(":8000", nil))
}

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


func getHealthHandler(writer http.ResponseWriter, request *http.Request) {
    serverUptime := time.Now().Sub(serverStartedTime)

    hours := int64(serverUptime.Hours())
    minutes := int64(serverUptime.Minutes()) - (hours * 60)
    seconds := int64(serverUptime.Seconds()) - (hours * 60) - (minutes * 60)
    nanoSeconds := int64(serverUptime.Nanoseconds()) - (hours * 60) - (minutes * 60) - (seconds * 1000000000)

    serverInformation := ServerInformation{
        ServerUptimeInformation{
            hours, minutes, seconds, nanoSeconds,
        },
    }

    returnJSON(writer, serverInformation)
}

func returnJSON(writer http.ResponseWriter, data ...interface{}) {
    dataJSON, marshalError := json.Marshal(data)

    if marshalError != nil {
        writer.WriteHeader(http.StatusInternalServerError)
    } else {
        writer.WriteHeader(http.StatusOK)
        writer.Header().Set("Content-Type", "application/json")
        writer.Write(dataJSON)
    }
}

默认情况下,go 会复制提供给方法的参数。 因此,“/api/v1/health”的 http 处理程序确实需要一个编写器,我们将其传递给 returnjson 方法。

因此,此方法确实收到了一个在其上写入的副本。

为什么我在浏览器中看到了响应? 我没想到,因为作者被复制了。


解决方案


你认为 ResponseWriter 是一个结构体,但它是一个接口。

每次将 writer http.responsewriter 发送到方法中时,都会发送指向实现该接口的结构的指针。

执行此行以查看实际类型:

fmt.Printf("%T\n", writer)

以上就是《值和引用》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>