GoLang

时间:2019-03-26 22:34:02

标签: rest go mux

我刚刚开始使用GoLang开发REST api。我在后端有一个带有某些方法的类。其余的api应该调用该类的方法之一,并返回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()函数中定义的对象的方法,然后返回json输出。

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

当我在主函数中声明宿主obj并尝试通过GetOSStats()函数访问它时,它将引发异常。

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

谢谢,

1 个答案:

答案 0 :(得分:2)

您要在本地重新声明host变量(也称为“阴影”)

host := new(objects.HostOS)

相反,您应该使用赋值运算符

host = new(objects.HostOS)