## 将GRPC导出为JSON API 在第六章的“理解GRPC的使用”一节中,我们实现了一个基础的GRPC服务器和客户端。本节将通过将常见的RPC函数放在一个包中并将它们包装在GRPC服务器和标准Web处理程序中来进行扩展。当你的API希望支持两种类型的客户端,但不希望复制代码以实现常见功能时,这非常有用。 ### 实践 1. 安装GRPC: https://github.com/grpc/grpc/blob/master/INSTALL.md. ``` go get github.com/golang/protobuf/proto go get github.com/golang/protobuf/protoc-gen-go ``` 2. 建立greeter.proto: ``` syntax = "proto3"; package keyvalue; service KeyValue{ rpc Set(SetKeyValueRequest) returns (KeyValueResponse){} rpc Get(GetKeyValueRequest) returns (KeyValueResponse){} } message SetKeyValueRequest { string key = 1; string value = 2; } message GetKeyValueRequest{ string key = 1; } message KeyValueResponse{ string success = 1; string value = 2; } ``` 运行 ``` protoc --go_out=plugins=grpc:. greeter.proto ``` 3. 建立 keyvalue.go: ``` package internal import ( "golang.org/x/net/context" "sync" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "google.golang.org/grpc" "google.golang.org/grpc/codes" ) type KeyValue struct { mutex sync.RWMutex m map[string]string } // NewKeyValue 初始化了KeyValue中的map func NewKeyValue() *KeyValue { return &KeyValue{ m: make(map[string]string), } } // Set 为键设置一个值,然后返回该值 func (k *KeyValue) Set(ctx context.Context, r *keyvalue.SetKeyValueRequest) (*keyvalue.KeyValueResponse, error) { k.mutex.Lock() k.m[r.GetKey()] = r.GetValue() k.mutex.Unlock() return &keyvalue.KeyValueResponse{Value: r.GetValue()}, nil } // Get 得到一个给定键的值,或者如果它不存在报告查找失败 func (k *KeyValue) Get(ctx context.Context, r *keyvalue.GetKeyValueRequest) (*keyvalue.KeyValueResponse, error) { k.mutex.RLock() defer k.mutex.RUnlock() val, ok := k.m[r.GetKey()] if !ok { return nil, grpc.Errorf(codes.NotFound, "key not set") } return &keyvalue.KeyValueResponse{Value: val}, nil } ``` 4. 建立 grpc/main.go: ``` package main import ( "fmt" "net" "github.com/agtorre/go-cookbook/chapter7/grpcjson/internal" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "google.golang.org/grpc" ) func main() { grpcServer := grpc.NewServer() keyvalue.RegisterKeyValueServer(grpcServer, internal.NewKeyValue()) lis, err := net.Listen("tcp", ":4444") if err != nil { panic(err) } fmt.Println("Listening on port :4444") grpcServer.Serve(lis) } ``` 5. 建立 set.go: ``` package main import ( "encoding/json" "net/http" "github.com/agtorre/go-cookbook/chapter7/grpcjson/internal" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "github.com/apex/log" ) // Controller 保存一个内部的KeyValueObject type Controller struct { *internal.KeyValue } // SetHandler 封装了RPC的Set调用 func (c *Controller) SetHandler(w http.ResponseWriter, r *http.Request) { var kv keyvalue.SetKeyValueRequest decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&kv); err != nil { log.Errorf("failed to decode: %s", err.Error()) w.WriteHeader(http.StatusBadRequest) return } gresp, err := c.Set(r.Context(), &kv) if err != nil { log.Errorf("failed to set: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } resp, err := json.Marshal(gresp) if err != nil { log.Errorf("failed to marshal: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Write(resp) } ``` 6. 建立 get.go: ``` package main import ( "encoding/json" "net/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "github.com/agtorre/go-cookbook/chapter7/grpcjson/keyvalue" "github.com/apex/log" ) // GetHandler 封装了RPC的Get调用 func (c *Controller) GetHandler(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") kv := keyvalue.GetKeyValueRequest{Key: key} gresp, err := c.Get(r.Context(), &kv) if err != nil { if grpc.Code(err) == codes.NotFound { w.WriteHeader(http.StatusNotFound) return } log.Errorf("failed to get: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) resp, err := json.Marshal(gresp) if err != nil { log.Errorf("failed to marshal: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } w.Write(resp) } ``` 7. 建立 main.go: ``` package main import ( "fmt" "net/http" "github.com/agtorre/go-cookbook/chapter7/grpcjson/internal" ) func main() { c := Controller{KeyValue: internal.NewKeyValue()} http.HandleFunc("/set", c.SetHandler) http.HandleFunc("/get", c.GetHandler) fmt.Println("Listening on port :3333") err := http.ListenAndServe(":3333", nil) panic(err) } ``` 8. 运行: ``` $ go run http/*.go Listening on port :3333 $curl "http://localhost:3333/set" -d '{"key":"test", "value":"123"}' -v {"value":"123"} $curl "http://localhost:3333/get?key=badtest" -v 'name=Reader;greeting=Goodbye' <should return a 404> $curl "http://localhost:3333/get?key=test" -v 'name=Reader;greeting=Goodbye' {"value":"123"} ``` ### 说明 虽然示例中省略了客户端,但你可以复制第6章GRPC章节中的步骤,这样应该看到与示例中相同的结果。http和grpc使用了相同的内部包。我们必须返回适当的GRPC错误代码,并将这些错误代码映射到HTTP响应。在这种情况下,我们使用codes.NotFound,它映射到http.StatusNotFound。如果必须处理多种错误,则switch语句可能比if ... else语句更有意义。 你可能注意到GRPC签名通常非常一致。他们接受请求并返回可选响应和错误。如果你的GRPC调用重复性很强并且看起来很适合代码生成,那么可以创建一个通用的处理程序来填充它,像 github.com/goadesign/goa 这样的库就是这么干的。 * * * * 学识浅薄,错误在所难免。欢迎在群中就本书提出修改意见,以飨后来者,长风拜谢。 Golang中国(211938256) beego实战(258969317) Go实践(386056972)