在 Go 语言中调用 REST 路由方法中的对象方法

Call object method in REST router method in GoLang

我刚刚开始使用 GoLang 开发 REST api。我有一个 class,后端有一些方法。其余 api 应调用 class 和 return 的方法之一 json 响应。我在调用对象方法或通过引用传递对象时遇到问题。我的鳕鱼看起来像这样。

package main

import (
    "time"
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "./objects")

/*Global Variables*/
var host objects.HostOS  // I have declared this to see if I can have a global variable and later on assign the actual object to that and call that object in the GetStats router method below. 

func main() {
    fmt.Println("Hello World")

    hostConfig := objects.HostConfig{CPUConfig: cpuConfig, MemoryKB: 4096, OSMemoryKB: 1024, OSCompute: 100}

    host := new(objects.HostOS)
    host.Init(hostConfig)

    host.Boot()
    time.Sleep(3 * time.Second)
    process := new(objects.Process)
    process.Init(objects.ProcessConfig{MinThreadCount: 2, MaxThreadCount: 8, ParentOSInstance: host})
    process.Start()

    router := mux.NewRouter().StrictSlash(true)

    router.HandleFunc("/", Index)
    router.HandleFunc("/get_os_stats", GetOSStats)

    log.Fatal(http.ListenAndServe(":8080", router))
    //host.GetStatsJson()
}


func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome!")
}

func GetOSStats(w http.ResponseWriter, r *http.Request) {
    // js, err := host.GetStatsJson()   // This is what I would like to do
    // Ideally I would get the Marshalled json and err and return them. 
    // The object method works fine as I have tested it, I am however unable to call the object method here. 

    fmt.Println("getting json stats")
    host.GetStatsJson()  //This is were I get the server panic issue and the code breaks
    //I would like to access the method of the 'host' object defined in the main() method. 
    fmt.Fprintln(w, "GetOSStats!")
}

我想在 GetOSStats() 方法中调用 main() 函数中定义的对象的方法,然后 return json 输出。

当我声明一个全局变量然后在主函数中对其赋值时,GetOSStats() 函数仍在访问一个 nil 结构。

当我在主函数中声明主机对象并尝试在 GetOSStats() 函数中访问它时,它抛出异常。

我想我必须通过引用 GetOSStats() 函数来传递主机 obj,同时在 main 中调用它,但我不确定该怎么做。我曾尝试查找文档和示例,但找不到任何可以帮助我的东西。

提前致谢,

您正在本地重新声明 host 变量(这也称为 "shadowing")

host := new(objects.HostOS)

您应该使用赋值运算符

host = new(objects.HostOS)