Мне немного интересно, почему работает следующий код:
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 копирует параметры, предоставляемые методам.Итак, обработчик HTTP для '/ api / v1 / health' действительно берет писателя, и мы передаем его методу returnJSON
.
Итак, этот метод получает копию, в которую он пишет.
Как получилось, что в моем браузере я вижу ответ?Я не ожидал этого, так как писатель копируется.