1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-24 20:52:22 +00:00

ch4-07: 完善细节

This commit is contained in:
chai2010 2018-07-22 11:54:00 +08:00
parent 2432290c6a
commit dffe10cec9

View File

@ -61,8 +61,6 @@ service HelloService {
在本章的第二节我们已经简单讲述过Protobuf插件的工作原理并且展示了如何生成RPC必要的代码。插件是一个generator.Plugin接口
```go
// A Plugin provides functionality to add to the output during Go code generation,
// such as to produce RPC stubs.
type Plugin interface {
// Name identifies the plugin.
Name() string
@ -70,7 +68,8 @@ type Plugin interface {
// code generation begins.
Init(g *Generator)
// Generate produces the code generated by the plugin for this file,
// except for the imports, by calling the generator's methods P, In, and Out.
// except for the imports, by calling the generator's methods P, In,
// and Out.
Generate(file *FileDescriptor)
// GenerateImports produces the import declarations for this file.
// It is called after Generate.
@ -106,9 +105,12 @@ pbgo为服务的方法定义了一个rest_api名字的扩展在最终生成
下面是getServiceMethodOption方法的实现
```go
func (p *pbgoPlugin) getServiceMethodOption(m *descriptor.MethodDescriptorProto) *pbgo.HttpRule {
func (p *pbgoPlugin) getServiceMethodOption(
m *descriptor.MethodDescriptorProto,
) *pbgo.HttpRule {
if m.Options != nil && proto.HasExtension(m.Options, pbgo.E_RestApi) {
if ext, _ := proto.GetExtension(m.Options, pbgo.E_RestApi); ext != nil {
ext, _ := proto.GetExtension(m.Options, pbgo.E_RestApi)
if ext != nil {
if x, _ := ext.(*pbgo.HttpRule); x != nil {
return x
}
@ -159,7 +161,9 @@ func HelloServiceHandler(svc HelloServiceInterface) http.Handler {
代码中选择的是开源中比较流行的httprouter路由引擎。其中_handle_HelloService_Hello_get函数用于将Hello方法注册到路由处理器
```go
func _handle_HelloService_Hello_get(router *httprouter.Router, svc HelloServiceInterface) {
func _handle_HelloService_Hello_get(
router *httprouter.Router, svc HelloServiceInterface,
) {
router.Handle("GET", "/hello/:value",
func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var protoReq, protoReply String
@ -190,7 +194,7 @@ func _handle_HelloService_Hello_get(router *httprouter.Router, svc HelloServiceI
## 启动REST服务
虽然从头构造pbgo框架的过程比较繁琐但是使用pbgo构造REST服务是异常简单。首先要构造一个满足HelloServiceInterface接口的服务对象
虽然从头构造pbgo框架的过程比较繁琐但是使用pbgo构造REST服务是异常简单。首先要构造一个满足HelloServiceInterface接口的服务对象
```go
import (