{"id":13471643,"url":"https://github.com/lileio/lile","last_synced_at":"2025-04-14T20:53:12.505Z","repository":{"id":53437532,"uuid":"80036106","full_name":"lileio/lile","owner":"lileio","description":"Easily generate gRPC services in Go ⚡️","archived":false,"fork":false,"pushed_at":"2023-07-19T07:05:49.000Z","size":312,"stargazers_count":1504,"open_issues_count":6,"forks_count":87,"subscribers_count":30,"default_branch":"master","last_synced_at":"2025-04-07T14:09:29.940Z","etag":null,"topics":["framework","go","grpc","microservice","prometheus","pubsub","zipkin"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lileio.png","metadata":{"files":{"readme":"README_zh-CN.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2017-01-25T17:04:51.000Z","updated_at":"2025-03-01T07:34:08.000Z","dependencies_parsed_at":"2022-09-17T04:50:45.523Z","dependency_job_id":"9c05f729-f78f-40fe-a6a6-63cc9713b620","html_url":"https://github.com/lileio/lile","commit_stats":{"total_commits":141,"total_committers":21,"mean_commits":6.714285714285714,"dds":0.6170212765957447,"last_synced_commit":"2b112ceae4ac6da1d274a1cdfcef7b476513ce1e"},"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lileio%2Flile","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lileio%2Flile/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lileio%2Flile/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lileio%2Flile/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lileio","download_url":"https://codeload.github.com/lileio/lile/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248961048,"owners_count":21189990,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["framework","go","grpc","microservice","prometheus","pubsub","zipkin"],"created_at":"2024-07-31T16:00:47.776Z","updated_at":"2025-04-14T20:53:12.480Z","avatar_url":"https://github.com/lileio.png","language":"Go","funding_links":[],"categories":["开源类库","Go","Open source library","Language-Specific","prometheus","zipkin","Repositories"],"sub_categories":["RPC","Go","Observability"],"readme":"![logo](https://raw.githubusercontent.com/lileio/lile/master/lile.png)\n\n\u003e **ALPHA:** Lile当前正处于Alpha版本，可能还会存在一些变化。目前，我正在收集反馈意见，并将尽快敲定Lile，以避免发生变化。\n\nLile是可以帮助您快速创建基于gRPC通讯，或者可以通过[gateway](https://github.com/grpc-ecosystem/grpc-gateway)创建REST通讯的发布订阅服务的一个生成器和工具集。\n\nLile主要是用于过创建基本结构，测试示例，Dockerfile，Makefile等基础骨架。\n\nLile也是一个简单的服务生成器，扩展了基本的gRPC服务器，包括诸如指标（如[Prometheus](prometheus.io)），跟踪（如[Zipkin](zipkin.io)）和发布订阅（如[Google PubSub](https://cloud.google.com/pubsub/docs/overview)等可插拔选项。\n\nLile在的Slack上的[Gopher Slack](https://invite.slack.golangbridge.org/) 交流渠道[#lile](https://gophers.slack.com/messages/C6RHLV3LN)\n\n[![Build Status](https://travis-ci.org/lileio/lile.svg?branch=master)](https://travis-ci.org/lileio/lile) [![GoDoc](https://godoc.org/github.com/lileio/lile?status.svg)](https://godoc.org/github.com/lileio/lile) [![Go Report Card](https://goreportcard.com/badge/github.com/lileio/lile)](https://goreportcard.com/report/github.com/lileio/lile) [![license](https://img.shields.io/github/license/mashape/apistatus.svg)]()\n\n[![asciicast](https://asciinema.org/a/rLAGV6nsdBreyWgXtb6bgL3Hb.png)](https://asciinema.org/a/rLAGV6nsdBreyWgXtb6bgL3Hb)\n\n### 安装\n\n安装Lile很容易，使用`go get`便可以安装Lile的命令行工具来生成新的服务和所需的库。\n\n```\n$ go get -u github.com/lileio/lile/...\n```\n\n您还需要安装Google的[Protocol Buffers](https://developers.google.com/protocol-buffers/)。\n\n### 入门\n\n通过执行`lile run`和一个短文件路径生成一个新的服务。\n\nLilek可以自动根据`username/service`生成一个完整的路径到`$GOPATH`下的`github.com`中。\n\n```\n$ lile new lileio/users\n```\n\n# 指南\n\n- [安装](#安装)\n- [创建服务](#创建服务)\n- [服务定义](#服务定义)\n- [生成RPC方法](#生成RPC方法)\n- [编写并运行测试](#编写并运行测试)\n- [使用生成的命令行](#使用生成的命令行)\n- [自定义命令行](#自定义命令行)\n- [暴露Prometheus指标](#暴露Prometheus采集指标)\n- [发布和订阅](#发布和订阅)\n- [发布事件](#发布事件)\n- [自动发布事件](#自动发布事件)\n- [订阅事件](#订阅事件)\n- [追踪](#追踪)\n\n## 安装\n\n首先，你需要确保您在您安装Lile之前已经安装了Go。\n\n安装Lile很容易，使用`go get`便可以安装Lile的命令行工具来生成新的服务和所需的库。\n\n```\n$ go get github.com/lileio/lile/...\n```\n\n您还需要安装Google的[Protocol Buffers][Protocol Buffers](https://developers.google.com/protocol-buffers/)。\n\n在MacOS你可以使用`brew install protobuf`来安装。\n\n## 创建服务\n\nLile使用生成器来快速生成新的Lile服务。\n\nLile遵循Go关于$GOPATH的约定（参见[如何写Go](https://golang.org/doc/code.html#Workspaces)），并且自动解析您的新服务的名称，以在正确的位置创建服务。\n\n如果您的Github用户名是lileio，并且您想创建一个新的服务为了发布消息到Slack，您可以使用如下命令：\n\n```\nlile new lileio/slack\n```\n\n这将创建一个项目到`$GOPATH/src/github.com/lileio/slack`\n\n## 服务定义\n\nLile服务主要使用gRPC，因此使用[protocol buffers](https://developers.google.com/protocol-buffers/)作为接口定义语言（IDL），用于描述有效负载消息的服务接口和结构。 如果需要，可以使用其他替代品。\n\n我强烈建议您先阅读[Google API设计](https://cloud.google.com/apis/design/)文档，以获得有关RPC方法和消息的一般命名的好建议，以及如果需要，可以将其转换为REST/JSON。\n\n您可以在Lile中发现一个简单的例子[`account_service`](https://github.com/lileio/account_service)\n\n``` protobuf\nservice AccountService {\n  rpc List (ListAccountsRequest) returns (ListAccountsResponse) {}\n  rpc GetById (GetByIdRequest) returns (Account) {}\n  rpc GetByEmail (GetByEmailRequest) returns (Account) {}\n  rpc AuthenticateByEmail (AuthenticateByEmailRequest) returns (Account) {}\n  rpc GeneratePasswordToken (GeneratePasswordTokenRequest) returns (GeneratePasswordTokenResponse) {}\n  rpc ResetPassword (ResetPasswordRequest) returns (Account) {}\n  rpc ConfirmAccount (ConfirmAccountRequest) returns (Account) {}\n  rpc Create (CreateAccountRequest) returns (Account) {}\n  rpc Update (UpdateAccountRequest) returns (Account) {}\n  rpc Delete (DeleteAccountRequest) returns (google.protobuf.Empty) {}\n}\n```\n\n## 生成RPC方法\n\n默认情况下，Lile将创建一个RPC方法和一个简单的请求和响应消息。\n\n``` protobuf\nsyntax = \"proto3\";\noption go_package = \"github.com/lileio/slack\";\npackage slack;\n\nmessage Request {\n  string id = 1;\n}\n\nmessage Response {\n  string id = 1;\n}\n\nservice Slack {\n  rpc Read (Request) returns (Response) {}\n}\n```\n\n我们来修改一下使它能够提供真正的服务，并添加自己的方法。\n\n我们来创建一个`Announce`方法向Slack发布消息。\n\n我们假设Slack团队和身份验证已经由服务配置来处理，所以我们服务的用户只需要提供一个房间和他们的消息。 该服务将发送特殊的空响应，因为我们只需要知道是否发生错误，也不需要知道其他任何内容。\n\n现在我们的`proto`文件看起来像这样：\n\n``` protobuf\nsyntax = \"proto3\";\noption go_package = \"github.com/lileio/slack\";\nimport \"google/protobuf/empty.proto\";\npackage slack;\n\nmessage AnnounceRequest {\n  string channel = 1;\n  string msg = 2;\n}\n\nservice Slack {\n  rpc Announce (AnnounceRequest) returns (google.protobuf.Empty) {}\n}\n```\n\n现在我们运行`protoc`工具我们的文件，以及Lile生成器插件。\n\n```\nprotoc -I . slack.proto --lile-server_out=. --go_out=plugins=grpc:$GOPATH/src\n```\n\nLile提供了一个`Makefile`，每个项目都有一个已经配置的`proto`构建步骤。 所以我们可以运行它。\n\n```\nmake proto\n```\n\n我们可以看到，Lile将在`server`目录中为我们创建两个文件。\n\n```\n$ make proto\nprotoc -I . slack.proto --lile-server_out=. --go_out=plugins=grpc:$GOPATH/src\n2017/07/12 15:44:01 [Creating] server/announce.go\n2017/07/12 15:44:01 [Creating test] server/announce_test.go\n```\n\n我们来看看Lile为我们创建的`announce.go`文件。\n\n``` go\npackage server\n\nimport (\n    \"errors\"\n\n    \"github.com/golang/protobuf/ptypes/empty\"\n    \"github.com/lileio/slack\"\n    context \"golang.org/x/net/context\"\n)\n\nfunc (s SlackServer) Announce(ctx context.Context, r *slack.AnnounceRequest) (*empty.Empty, error) {\n  return nil, errors.New(\"not yet implemented\")\n}\n```\n\n接下来我们实现这个生成的方法，让我们从测试开始吧！\n\n\n## 编写并运行测试\n\n当您使用Lile生成RPC方法时，也会创建一个对应的测试文件。例如，给定我们的`announce.go`文件，Lile将在同一目录中创建`announce_test.go`\n\n看起来如下:\n\n``` go\npackage server\n\nimport (\n\t\"testing\"\n\n\t\"github.com/lileio/slack\"\n\t\"github.com/stretchr/testify/assert\"\n\tcontext \"golang.org/x/net/context\"\n)\n\nfunc TestAnnounce(t *testing.T) {\n\tctx := context.Background()\n\treq := \u0026slack.AnnounceRequest{}\n\n\tres, err := cli.Announce(ctx, req)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, res)\n}\n\n```\n\n您现在可以使用`Makefile`运行测试，并运行`make test`命令\n\n```\n$ make test\n=== RUN   TestAnnounce\n--- FAIL: TestAnnounce (0.00s)\n        Error Trace:    announce_test.go:16\n        Error:          Expected nil, but got: \u0026status.statusError{Code:2, Message:\"not yet implemented\", Details:[]*any.Any(nil)}\n        Error Trace:    announce_test.go:17\n        Error:          Expected value not to be nil.\nFAIL\ncoverage: 100.0% of statements\nFAIL    github.com/lileio/slack/server  0.011s\nmake: *** [test] Error 2\n\n```\n\n我们的测试失败了，因为我们还没有实现我们的方法，在我们的方法中返回一个“未实现”的错误。\n\n让我们在`announce.go`中实现`Announce`方法，这里是一个使用`nlopes`的[slack library](https://github.com/nlopes/slack)的例子。\n\n``` go\npackage server\n\nimport (\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"github.com/golang/protobuf/ptypes/empty\"\n\t\"github.com/lileio/slack\"\n\tsl \"github.com/nlopes/slack\"\n\tcontext \"golang.org/x/net/context\"\n)\n\nvar api = sl.New(os.Getenv(\"SLACK_TOKEN\"))\n\nfunc (s SlackServer) Announce(ctx context.Context, r *slack.AnnounceRequest) (*empty.Empty, error) {\n\t_, _, err := api.PostMessage(r.Channel, r.Msg, sl.PostMessageParameters{})\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, err.Error())\n\t}\n\n\treturn \u0026empty.Empty{}, nil\n}\n```\n\n我们再次修改我们的测试用力，然后再次运行我们的测试\n\n``` go\npackage server\n\nimport (\n\t\"testing\"\n\n\t\"github.com/lileio/slack\"\n\t\"github.com/stretchr/testify/assert\"\n\tcontext \"golang.org/x/net/context\"\n)\n\nfunc TestAnnounce(t *testing.T) {\n\tctx := context.Background()\n\treq := \u0026slack.AnnounceRequest{\n\t\tChannel: \"@alex\",\n\t\tMsg:     \"hellooo\",\n\t}\n\n\tres, err := cli.Announce(ctx, req)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, res)\n}\n```\n现在如果我使用我的Slack令牌作为环境变量运行测试，我应该看到通过测试！\n\n```\n$ alex@slack: SLACK_TOKEN=zbxkkausdkasugdk make test\ngo test -v ./... -cover\n?       github.com/lileio/slack [no test files]\n=== RUN   TestAnnounce\n--- PASS: TestAnnounce (0.32s)\nPASS\ncoverage: 75.0% of statements\nok      github.com/lileio/slack/server  0.331s  coverage: 75.0% of statements\n?       github.com/lileio/slack/slack   [no test files]\n?       github.com/lileio/slack/slack/cmd       [no test files]\n?       github.com/lileio/slack/subscribers     [no test files]\n```\n\n## 使用生成的命令行\n\n生成您的服务时，Lile生成一个命令行应用程序。 您可以使用自己的命令行扩展应用程序或使用内置的命令行来运行服务。\n\n运行没有任何参数的命令行应用程序将打印生成的帮助。\n\n例如`go run orders/main.go`\n\n### 服务\n\n运行`serve`将运行RPC服务。\n\n### 订阅\n\n运行`subscribe`订阅者将会收到你的订阅发布事件。\n\n### up\n\n运行`up`将同时运行RPC服务器和发布订阅的订阅者。\n\n## 自定义命令行\n\n要添加您自己的命令行，您可以使用[cobra](https://github.com/spf13/cobra)，它是Lile的内置的命令行生成器。\n\n``` bash\n$ cd orders\n$ cobra add import\n```\n\n您现在可以编辑生成的文件，以创建您的命令行，`cobra`会自动将命令行的名称添加到帮助中。 \n\n## 暴露Prometheus采集指标\n\n默认情况下，Lile将[Prometheus](prometheus.io)的采集指标暴露在`:9000/metrics`。\n\n如果您的服务正在运行，您可以使用cURL来预览Prometheus指标。\n\n```\n$ curl :9000/metrics\n```\n\n你应该看到如下的一些输出：\n\n```\n# HELP go_gc_duration_seconds A summary of the GC invocation durations.\n# TYPE go_gc_duration_seconds summary\ngo_gc_duration_seconds{quantile=\"0\"} 0\ngo_gc_duration_seconds{quantile=\"0.25\"} 0\ngo_gc_duration_seconds{quantile=\"0.5\"} 0\ngo_gc_duration_seconds{quantile=\"0.75\"} 0\ngo_gc_duration_seconds{quantile=\"1\"} 0\ngo_gc_duration_seconds_sum 0\ngo_gc_duration_seconds_count 0\n...\n...\n```\n\nLile的Prometheus指标实现使用go-grpc-promesheus的拦截器将其内置到自身的gPRC中，提供如以下的指标：\n\n```\ngrpc_server_started_total\ngrpc_server_msg_received_total\ngrpc_server_msg_sent_total\ngrpc_server_handling_seconds_bucket\n```\n\n有关使用Prometheus的更多信息，收集和绘制这些指标，请参阅[Prometheus入门](https://prometheus.io/docs/introduction/getting_started/)\n\n有关gRPC Prometheus查询的示例，请参阅[查询示例](https://github.com/grpc-ecosystem/go-grpc-prometheus#useful-query-examples)。\n\n## 发布和订阅\n\n虽然大多数服务将主要通过RPC进行通信，但Lile提供了一个[pubsub](https://github.com/lileio/lile/tree/master/pubsub)来执行[Publish \u0026 Subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)通信，这在开发异步的请求时特别有用。\n\nYou can either manually publish events or use the gRPC [middleware](https://github.com/lileio/lile/blob/master/pubsub/interceptor.go) to automatically publish an event when a RPC method is called.\n\n发布者与订阅者是松耦合的，甚至不知道它们的存在。大多数[Lile](https://github.com/lileio)已经内置了事件钩子，但是您也可以很容易的添加事件到您的服务中。您可以手动发布事件或使用gRPC[中间件](https://github.com/lileio/lile/blob/master/pubsub/interceptor.go)在调用RPC方法时自动发布事件。\n\nLile的发布订阅是基于每个用户存在“至少一次”消息传递。换句话说，给定一个发布事件`account_created`的`account_service`（发布者），如果`email_service`（subscriber）和`fraud_detection_service`（subscriber）的多个实例正在运行，则每个`email_service`和`fraud_detection_service`都只有一个实例收到一条消息。\n\n## 发布事件\n\n如果配置了发布订阅（通过环境自动或手动进行），那么只需要一个简单的“Publish”调用。\n\n以下是“订单”服务的“Get”方法示例：\n\n``` go\nfunc (s OrdersServer) Get(ctx context.Context, r *orders.GetRequest) (*orders.GetResponse, error) {\n\to, err := getOrder(r.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := \u0026orders.GetResponse{\n\t\tId:   o.Id,\n\t\tName: o.Name,\n\t}\n\tpubsub.Publish(ctx, \"orders_service.Get\", res)\n\treturn res, nil\n}\n```\n\n`Publish`需要一个`context.Context`用于跟踪和指标，一个主题名称和一个`proto.Msg`，它是可以序列化到protobuf的任何对象。\n\n## 自动发布事件\n\n当使用了Lile的gPRC[中间件](https://github.com/lileio/lile/blob/master/pubsub/interceptor.go)，在调用gRPC方法时，可以自动发布事件。\n\n在我们的`main.go`中，我们可以添加发布订阅拦截器，将我们的gRPC方法映射到我们的发布订阅主题。\n\n拦截器将自动发布gRPC响应到该主题。\n\n``` go\nlile.AddPubSubInterceptor(map[string]string{\n\t\"Create\": \"account_service.created\",\n\t\"Update\": \"account_service.updated\",\n})\n```\n\n## 订阅事件\n\n默认情况下，Lile将在项目中生成一个具有一些订阅事件基本设置的`subscribers.go`文件。\n\n[`lile.Subscriber`](https://godoc.org/github.com/lileio/lile/pubsub#Subscriber)借口用于订阅符合`Setup`事件规范任何主题的事件。\n```go\ntype OrdersServiceSubscriber struct{}\n\nfunc (s *OrdersServiceSubscriber) Setup(c *pubsub.Client) {\n\tc.On(\"shipments.updated\", s.ShipmentUpdate, 30*time.Second, true)\n}\n\nfunc (s *OrdersServiceSubscriber) ShipmentUpdate(sh *shipments.Shipment) {\n\t// do something with sh\n}\n```\n\n[Handler interface](https://godoc.org/github.com/lileio/lile/pubsub#Handler)是用于监听符合发布订阅的任何内容的功能。\n\nProtobuf消息自动解码。\n\n## 追踪\n\nLile已经建立了跟踪，将[opentracing](http://opentracing.io/) 兼容的跟踪器设置为`GlobalTracer`，默认情况下，Lile报告所有gRPC方法和发布/订阅操作。\n\n![](https://2.bp.blogspot.com/-0pFWb8zb-Cg/WPb9qKoDwDI/AAAAAAAAD2g/VjUFl1-_tYgy6zpzw0iyjfwh3gh0rg92wCLcB/s640/go-2.png)\n\n### Zipkin\n\n要通过HTTP将所有跟踪事件发送到[Zipkin](http://zipkin.io)，请将环境变量`ZIPKIN_SERVICE_HOST`设置为Zipkin服务的DNS名称。 如果服务已经运行命名为“zipkin”，Kubernetes将自动将`ZIPKIN_SERVICE_HOST`暴露给容器。\n\n### Stackdriver (Google Cloud Platform) Trace\n\n如果你想使用追踪而又不想维护Zipkin，Stackdriver提供了一个`zipkin-collector`映像，它将侦听Zipkin跟踪，转换并发送到Stackdriver。更多请参阅[Google Cloud Tracing](https://cloud.google.com/trace/docs/zipkin#option_1_using_a_container_image_to_set_up_your_server)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flileio%2Flile","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flileio%2Flile","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flileio%2Flile/lists"}