【问题标题】:Call object method in REST router method in GoLang在 GoLang 的 REST 路由器方法中调用对象方法
【发布时间】:2019-08-17 10:13:27
【问题描述】:

我刚刚开始使用 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 结构。

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

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

提前致谢,

【问题讨论】:

    标签: rest go mux


    【解决方案1】:

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

    host := new(objects.HostOS)
    

    你应该使用赋值运算符

    host = new(objects.HostOS)
    

    【讨论】:

    • 感谢@zerkms 指出我的错误。建议的更改奏效了。
    • @zerkms 关于您的 MDN 问题,我更新了规范 URL 以引用 tc39.github.io/ecma262 位置,而不是现在已过时的 ecma-international.org/ecma-262/9.0 (ES2018) 位置。当前的 MDN 政策是始终使用 {{SpecName('ESDraft', …)}} 宏来引用 ES 规范(而不是使用 {{SpecName('ES2018', …)}} 或任何旧的 ES 规范版本)。如果您想讨论该政策,irc.mozilla.org 上的#mdn 频道是个不错的地方。或discourse.mozilla.org/c/mdn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2020-11-18
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多