dongningce9075 2018-06-14 08:16
浏览 95

如何使用gRPC创建rest API以读取go lang中的文本或任何文件?

I am trying to create a REST API in go programming language, to read the text file.

I want to build it using gRPC.

  • 写回答

1条回答 默认 最新

  • duancan8382 2018-06-14 08:31
    关注

    You could follow the Go introduction that's in the gRPC docs.

    The basic process is as follows:

    1) Write the Protocol Buffers definitions for your data structures and a gRPC service definition that integrates them:

    package fileserver
    
    message FileRequest {
      string name = 1;
    }
    
    message FileResponse {
      bytes contents = 1;
    }
    
    service FileServer {
      rpc ReadFile (FileRequest) returns (FileResponse) {}
    }
    

    2) Generate the gRPC/PB bindings using the "protoc" tool (you will need "protoc-gen-go" as well). The command is usually:

    protoc --go_out=plugins=grpc:. *.proto
    

    3) Implement the server:

    type FileServer struct{}
    
    func (s *FileServer) Dispatch(ctx context.Context, fileRequest *fileserver.FileRequest) (*fileserver.FileResponse, error) {
      f, _ := ioutil.ReadFile(fileRequest.Name)
      fileResponse := &fileserver.FileResponse{Contents: f}
      return fileResponse, nil
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)