15分钟
4.7.4 启动REST服务
虽然从头构造pbgo框架的过程比较繁琐,但是使用pbgo构造REST服务却是异常简单。首先要构造一个满足HelloServiceInterface接口的服务对象:
import (
"github.com/chai2010/pbgo/examples/hello.pb"
)
type HelloService struct{}
func (p *HelloService) Hello(request *hello_pb.String, reply *hello_pb.String) error {
reply.Value = "hello:" + request.GetValue()
return nil
}和RPC代码一样,在Hello方法中简单返回结果。然后调用该服务对应的HelloServiceHandler函数生成路由处理器,并启动服务:
func main() {
router := hello_pb.HelloServiceHandler(new(HelloService))
log.Fatal(http.ListenAndServe(":8080", router))
}然后在命令行测试REST服务:
$ curl localhost:8080/hello/vgo这样一个超级简单的pbgo框架就完成了!
学员评价