【发布时间】: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 中调用它,但我不确定如何做到这一点。我尝试查找文档和示例,但找不到任何可以帮助我的东西。
提前致谢,
【问题讨论】: