rest - 使用 Gobot.io 和 sleepy RESTful Framework for Go 执行 SparkCore 函数

标签 rest go sparkcore gobot.io

我有以下代码,其中我使用 Go 的 RESTful 框架,名为 sleepy .

我可以成功启动服务:http://localhost:3000 ,但是当我尝试访问 http://localhost:3000/temperature 时我正在等待我的SparkCore要执行的函数dht

我正在使用Gobot.io Spark platform根据 this example 执行此函数,我已经在自己的代码中实现了。

问题是代码没有通过 Get() 函数内的 gobot.Start() 方法,因此我实际上无法返回 结果数据。

我正在设置data值,希望我可以做到:

return 200, data, http.Header{"Content-type": {"application/json"}}

但由于 gobot.Start(),它永远不会被调用。

我对 Go 非常陌生,因此我们将不胜感激。

package main

import (
    "net/url"
    "net/http"
    "fmt"
    "github.com/dougblack/sleepy"
    "github.com/hybridgroup/gobot"
    "github.com/hybridgroup/gobot/platforms/spark"
)

var gbot = gobot.NewGobot()
var sparkCore = spark.NewSparkCoreAdaptor("spark", "device_id", "auth_token")

type Temperature struct {}
func (temperature Temperature) Get(values url.Values, headers http.Header) (int, interface{}, http.Header) {
    work := func() {
        if result, err := sparkCore.Function("dht", ""); err != nil {
            fmt.Println(err)
        } else {
            data := map[string]string{"Temperature": result}
            fmt.Println("result from \"dht\":", result)
        }
    }

    robot := gobot.NewRobot("spark",
        []gobot.Connection{sparkCore},
        work,
    )

    gbot.AddRobot(robot)
    gbot.Start()

    return 200, data, http.Header{"Content-type": {"application/json"}}
}

func main() {
    api := sleepy.NewAPI()

    temperatureResource := new(Temperature)
    api.AddResource(temperatureResource, "/temperature")

    fmt.Println("Listening on http://localhost:3000/")
    api.Start(3000)
}

最佳答案

gbot.Start() 是一个阻塞调用。

在这种情况下,您应该将其称为:

go gbot.Start() 

这将在 goroutine(想想线程)中启动它,然后让您的应用程序继续。

当您查看gobot example app时,它们不在后台运行,因为它是主要功能。如果 main 在后台运行所有内容并且不等待任何内容,则应用程序会立即退出,不会产生明显效果。

关于rest - 使用 Gobot.io 和 sleepy RESTful Framework for Go 执行 SparkCore 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29247254/

相关文章:

java - 如何在没有返回类型或回调的情况下执行 DELETE 请求? [ retrofit ]

performance - 批量http请求

go - 在 golang 中寻找合理的堆栈实现?

c++ - Arduino 触摸代码不适用于 spark 核心

c# - HttpRequestMessage.Content 在 ASP.Net Web API 中的日志记录 DelegatingHandler 中读取时丢失

ios - 为 Alamofire 请求输入用户名和密码

string - 我可以删除字符串表示([]byte)中的尾随零来比较字符串吗?

macos - 操作系统 : Code-sign executable to avoid firewall warning dialog

c++ - 如何计算当月的星期日?