dsq1982 2015-03-25 04:06
浏览 40
已采纳

使用Gobot.io和昏昏欲睡的RESTful Framework for Go执行SparkCore功能

I have the following bit of code where I'm using the RESTful framework for Go called sleepy.

I can successfully start the service at: http://localhost:3000, however when I try to access http://localhost:3000/temperature I'm expecting my SparkCore function dht to execute.

I'm using the Gobot.io Spark platform to execute this function based on this example, which I've implemented in my own code.

The problem is that the code doesn't get past the gobot.Start() method inside the Get() function so I can't actually return the result data.

I'm setting the data value hoping that I can do the:

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

But it never gets called becuase of the gobot.Start().

I'm very new to Go so any help would be greatly appreciated.

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)
}
  • 写回答

1条回答 默认 最新

  • douyao4632 2015-03-25 11:42
    关注

    gbot.Start() is a blocking call.

    In this context, you are expected to call it as:

    go gbot.Start() 
    

    This will launch it in a goroutine (think thread) and then let your app continue.

    When you look at the gobot example app, they don't run in the background since it is the main function. If main runs everything in the background and doesn't wait for anything, the app exits immediately with no apparent effect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏