{"id":13753609,"url":"https://github.com/micro-plat/hydra","last_synced_at":"2026-01-17T11:55:25.602Z","repository":{"id":31988084,"uuid":"131117010","full_name":"micro-plat/hydra","owner":"micro-plat","description":"后端一站式微服务框架，提供API、web、websocket，RPC、任务调度、消息消费服务器","archived":false,"fork":false,"pushed_at":"2025-03-17T01:45:43.000Z","size":108397,"stargazers_count":591,"open_issues_count":18,"forks_count":94,"subscribers_count":28,"default_branch":"master","last_synced_at":"2025-08-15T06:41:58.674Z","etag":null,"topics":["apiserver","backend","cron","cronjob","http-server","microservice","mq-consumer","rpc","rpcserver","web-websocket-rpc","webserver","websocket"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/micro-plat.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-04-26T07:27:46.000Z","updated_at":"2025-07-29T14:53:25.000Z","dependencies_parsed_at":"2023-11-20T06:48:03.925Z","dependency_job_id":"08ea77d2-59ac-452d-8308-b6fd759beecc","html_url":"https://github.com/micro-plat/hydra","commit_stats":{"total_commits":2368,"total_committers":11,"mean_commits":"215.27272727272728","dds":"0.31545608108108103","last_synced_commit":"562aed234d872dbd6e9841563bc54720eb6a737e"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"purl":"pkg:github/micro-plat/hydra","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/micro-plat%2Fhydra","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/micro-plat%2Fhydra/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/micro-plat%2Fhydra/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/micro-plat%2Fhydra/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/micro-plat","download_url":"https://codeload.github.com/micro-plat/hydra/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/micro-plat%2Fhydra/sbom","scorecard":{"id":642757,"data":{"date":"2025-08-11","repo":{"name":"github.com/micro-plat/hydra","commit":"49f097bfcf230ca510d5ba84973ac8d2fa3a4b37"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":1.5,"checks":[{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Code-Review","score":0,"reason":"Found 0/30 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"License","score":0,"reason":"license file not detected","details":["Warn: project does not have a license file"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"SAST","score":0,"reason":"no SAST tool detected","details":["Warn: no pull requests merged into dev branch"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Pinned-Dependencies","score":2,"reason":"dependency not pinned by hash detected -- score normalized to 2","details":["Warn: goCommand not pinned by hash: vendor/github.com/json-iterator/go/build.sh:10","Warn: goCommand not pinned by hash: vendor/google.golang.org/grpc/regenerate.sh:35","Warn: goCommand not pinned by hash: vendor/google.golang.org/grpc/vet.sh:37","Info:   1 out of   4 goCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Vulnerabilities","score":0,"reason":"12 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GO-2021-0052 / GHSA-h395-qcrw-5vmq","Warn: Project is vulnerable to: GHSA-3vp4-m3rf-835h","Warn: Project is vulnerable to: GO-2023-1737 / GHSA-2c4m-59x9-fr2g","Warn: Project is vulnerable to: GHSA-h74j-692g-48mq","Warn: Project is vulnerable to: GO-2025-3605 / GHSA-7vpp-9cxj-q8gv","Warn: Project is vulnerable to: GO-2024-2698 / GHSA-rhh4-rh7c-7r5v","Warn: Project is vulnerable to: GO-2024-3321 / GHSA-v778-237x-gjrc","Warn: Project is vulnerable to: GO-2025-3487 / GHSA-hcg3-q754-cr77","Warn: Project is vulnerable to: GO-2024-3333","Warn: Project is vulnerable to: GO-2025-3503 / GHSA-qxp5-gwg8-xv66","Warn: Project is vulnerable to: GO-2025-3595 / GHSA-vvgc-356p-c3xw","Warn: Project is vulnerable to: GO-2024-2611 / GHSA-8r3f-844c-mc37"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-21T11:16:18.973Z","repository_id":31988084,"created_at":"2025-08-21T11:16:18.973Z","updated_at":"2025-08-21T11:16:18.973Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28508462,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-17T11:50:55.898Z","status":"ssl_error","status_checked_at":"2026-01-17T11:50:55.569Z","response_time":85,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["apiserver","backend","cron","cronjob","http-server","microservice","mq-consumer","rpc","rpcserver","web-websocket-rpc","webserver","websocket"],"created_at":"2024-08-03T09:01:25.628Z","updated_at":"2026-01-17T11:55:25.568Z","avatar_url":"https://github.com/micro-plat.png","language":"Go","funding_links":[],"categories":["zookeeper"],"sub_categories":[],"readme":"[hydra](https://github.com/micro-plat/hydra)微服务容器\r\n======================\r\n基于golang实现。\r\n\r\nhydra 提供简单的、统一的、易扩展的服务容器框架。通过少量的代码集成，即可实现的丰富功能，如：集群管理、配置管理、服务注册与发现、系统监控、日志归集、链路追踪、安全访问、常用组件等。\r\n\r\n目前已应用于50+生产项目，主要功能：\r\n示例项目：[产研任务管理系统](https://gitee.com/emshop/workspace/)\r\n\r\n\r\n- #### ✓  六类服务\r\n   支持*API*、*WEB*、*WEBSOCKET*、*RPC*、*定时任务*、*消息消费* 等服务器，可在单个应用中组合使用。\r\n\r\n- #### ✓ 跨平台\r\n    支持windows, mac, linux以服务方式安装、运行、停止、卸载等。\r\n\r\n- #### ✓ 多种部署\r\n  支持分布式集群部署、单机伪集群部署、单机部署。\r\n\r\n- #### ✓ 多种集群\r\n\r\n    提供对等、分片、主从等集群模式。\r\n\r\n\r\n- #### ✓ 配置管理\r\n    采用配置中心，中心化管理配置，本地零配置。支持zookeeper, redis, 本地文件，进程内管理配置。\r\n\r\n - #### ✓ 热更新\r\n    配置变更后自动生效，无须手动重启服务\r\n\r\n- #### ✓ 注册与发现\r\n    支持zookeeper, etcd, redis等作为注册中心，为远程调用提供服务管理。\r\n\r\n- #### ✓ 业务监控\r\n\r\n    支持将metric信息(如：QPS、处理时长、响应等)定时上报到influxdb，用于系统运行状况监控大屏显示。\r\n\r\n- #### ✓ 链路跟踪\r\n\r\n    支持Skywalking，Cat等APM工具进行分布式追踪、性能指标分析、应用和服务依赖分析。\r\n- #### ✓ 日志归集\r\n\r\n    支持将本地日志提交到日志归集服务器( [rlog](https://github.com/micro-plat/rlog))，用于日志集中查询分析。\r\n\r\n   \r\n\r\n- #### ✓ 访问控制\r\n  \r\n    支持白名单、黑名单访问控制，Basic Auth、API KEY、Cookie, JWT等安全验证。\r\n    支持远程认证服务, 提供加解密、验证签等服务。\r\n\r\n- #### ✓ 服务器限流\r\n    支持服务器限流、降级、熔断等控制。\r\n\r\n- #### ✓ 灰度发布\r\n\r\n    支持根据业务规则编写灰度脚本，将用户请求转发到不同集群。\r\n\r\n- #### ✓ 提供常用组件库\r\n\r\n    redis,memcached,数据库，mqtt,activeMQ,rpc,uuid,分布式锁，http client,rpc client等。\r\n\r\n\r\n[hydra](https://github.com/micro-plat/hydra)\r\n\r\n\r\n- [hydra微服务容器](#hydra微服务容器)\r\n  - [一、示例](#一示例)\r\n  - [二、组合服务](#二组合服务)\r\n  - [三、 服务器配置](#三-服务器配置)\r\n      - [1. 设置平台、系统、集群名称](#1-设置平台系统集群名称)\r\n      - [2. 运行时 通过cli参数指定平台、系统、集群名称](#2-运行时-通过cli参数指定平台系统集群名称)\r\n      - [3. *API*监听端口：](#3-api监听端口)\r\n      - [4. *API*超时时长](#4-api超时时长)\r\n      - [5. 白名单、黑名单](#5-白名单黑名单)\r\n      - [6. JWT认证](#6-jwt认证)\r\n      - [7. 灰度发布](#7-灰度发布)\r\n      - [8. 自定义输出格式](#8-自定义输出格式)\r\n      - [9. 数据库配置](#9-数据库配置)\r\n      - [10. 缓存配置](#10-缓存配置)\r\n  - [四、 服务注册](#四-服务注册)\r\n  - [五、 服务响应](#五-服务响应)\r\n    - [🐿️联系作者](#️联系作者)\r\n    - [💲捐赠 🥣](#捐赠-)\r\n\r\n\r\n\r\n\r\n## 一、示例\r\n\r\n- ### 1. 构建API服务\r\n```go\r\npackage main\r\n\r\nimport (\r\n    \"github.com/micro-plat/hydra\"\r\n    \"github.com/micro-plat/hydra/hydra/servers/http\"\r\n)\r\n\r\nfunc main() {\r\n\r\n    //创建app\r\n\tapp := hydra.NewApp(\r\n            hydra.WithPlatName(\"test\"), //平台名\r\n            hydra.WithSystemName(\"apiserver\"), //系统或应用名\r\n            hydra.WithServerTypes(http.API),\r\n    )\r\n\r\n    //注册服务\r\n    app.API(\"/hello\", func(ctx hydra.IContext) interface{} {\r\n        return \"hello world\"\r\n    })\r\n\r\n    //启动app\r\n    app.Start()\r\n}\r\n```\r\n- ### 2. 构建RPC服务\r\n\r\n```go\r\npackage main\r\n\r\nimport (\r\n    \"github.com/micro-plat/hydra\"\r\n    \"github.com/micro-plat/hydra/hydra/servers/rpc\"\r\n)\r\n\r\nfunc main() {\r\n\r\n    //创建app\r\n\tapp := hydra.NewApp(\r\n            hydra.WithServerTypes(rpc.RPC),\r\n    )\r\n\r\n    //注册服务\r\n    app.RPC(\"/hello\", func(ctx hydra.IContext) interface{} {\r\n        return \"hello world\"\r\n    })\r\n\r\n    //启动app\r\n    app.Start()\r\n}\r\n```\r\n- ### 3. 构建定时任务服务\r\n\r\n```go\r\npackage main\r\n\r\nimport (\r\n    \"github.com/micro-plat/hydra\"   \r\n    \"github.com/micro-plat/hydra/hydra/servers/cron\"\r\n)\r\n\r\nfunc main() {\r\n\r\n\tapp := hydra.NewApp(\r\n            hydra.WithServerTypes(cron.CRON),\r\n    )\r\n   \r\n   //注册服务\r\n    app.CRON(\"/hello\",hello,\"@every 5s\")   \r\n    app.Start()\r\n}\r\nfunc hello(ctx hydra.IContext) interface{} {\r\n        return \"success\"\r\n}\r\n```\r\n- ### 4. 构建消息消费服务\r\n\r\n```go\r\npackage main\r\n\r\nimport (\r\n    \"github.com/micro-plat/hydra\"\r\n    \"github.com/micro-plat/hydra/hydra/servers/mqc\"\r\n    \"github.com/micro-plat/hydra/conf/vars/queue/lmq\"\r\n)\r\n\r\nfunc main() {\r\n\r\n\tapp := hydra.NewApp(\r\n            hydra.WithServerTypes(mqc.MQC),\r\n    )\r\n\r\n    //注册服务\r\n    app.MQC(\"/hello\",hello,\"queue-name\")\r\n\r\n    //设置消息队列服务器(本地内存MQ，支持redis,mqtt等)  \r\n    hydra.Conf.MQC(lmq.MQ)\r\n\r\n    app.Start()\r\n}\r\n\r\nfunc hello(ctx hydra.IContext) interface{} {\r\n        return \"success\"\r\n}\r\n```\r\n\r\n\r\n## 二、组合服务\r\n\r\n```go\r\npackage main\r\n\r\nimport (\r\n    \"github.com/micro-plat/hydra\"   \r\n     \"github.com/micro-plat/hydra/hydra/servers/http\"\r\n     \"github.com/micro-plat/hydra/hydra/servers/cron\"\r\n)\r\n\r\nfunc main() {\r\n\r\n\tapp := hydra.NewApp(\r\n            hydra.WithServerTypes(http.API,cron.CRON),\r\n    )\r\n\r\n    app.API(\"/hello\",hello)\r\n    app.CRON(\"/hello\",hello,\"@every 5s\") \r\n    app.Start()\r\n}\r\nfunc hello(ctx hydra.IContext) interface{} {\r\n        return \"hello world\"\r\n}\r\n```\r\n\r\n\r\n```sh\r\n$ ./flowserver run --plat test\r\n```\r\n\r\n日志如下：\r\n```sh\r\n[2020/07/08 09:36:31.140432][i][29f63e41d]初始化: /test/flowserver/api-cron/1.0.0/conf\r\n[2020/07/08 09:36:31.143027][i][29f63e41d]启动[api]服务...\r\n[2020/07/08 09:36:31.643524][i][b65655312]启动成功(api,http://192.168.4.121:8080,1)\r\n[2020/07/08 09:36:31.643885][i][29f63e41d]启动[cron]服务...\r\n[2020/07/08 09:36:31.844844][i][3908a5ccc]启动成功(cron,cron://192.168.4.121,1)\r\n[2020/07/08 09:36:32.346047][d][3908a5ccc]当前server启动为: master\r\n[2020/07/08 09:36:36.648149][i][01751ece6]cron.request: GET /hello from 192.168.4.121\r\n[2020/07/08 09:36:36.648244][i][01751ece6]cron.response: GET /hello 200  193.356µs\r\n[2020/07/08 09:36:41.651858][i][00f45e17b]cron.request: GET /hello from 192.168.4.121\r\n[2020/07/08 09:36:41.651911][i][00f45e17b]cron.response: GET /hello 200  159.694µs\r\n```\r\n\r\n服务已启动，cron server开始周期(每隔5秒)执行任务\r\n\r\n\r\n```sh\r\n$ curl http://192.168.4.121:8080/hello\r\n```\r\n返回内容：\r\n```sh\r\nhello world\r\n```\r\n\r\n\r\n## 三、 服务器配置\r\n\r\n\r\n#### 1. 设置平台、系统、集群名称\r\n\r\n```go\r\n\tapp := hydra.NewApp(\r\n            hydra.WithPlatName(\"test\"),\r\n            hydra.WithSystemName(\"apiserver\"),\r\n            hydra.WithServerTypes(http.API),\r\n            hydra.WithClusterName(\"prod\"),\t\t\t\r\n    )\r\n    app.Start()\r\n\r\n```\r\n\r\n#### 2. 运行时 通过cli参数指定平台、系统、集群名称\r\n\r\n```go\r\n\tapp := hydra.NewApp(\r\n            hydra.WithServerTypes(http.API),\t\r\n    )\r\n    app.Start()\r\n\r\n```\r\n\r\n#### 3. *API*监听端口：\r\n```go\r\n\thydra.Conf.API(\"8090\")\t\r\n```\r\n\r\n#### 4. *API*超时时长\r\n```go\r\n\thydra.Conf.API(\"8090\", api.WithHeaderReadTimeout(30), api.WithTimeout(30, 30)) \r\n```\r\n\r\n#### 5. 白名单、黑名单\r\n```go\r\n    hydra.Conf.API(\"8080\").\t\t\t\r\n\tWhiteList(whitelist.NewIPList(\"/**\", whitelist.WithIP(\"192.168.4.121\"))).\r\n\tBlackList(blacklist.WithIP(\"192.168.4.120\"))\r\n```\r\n#### 6. JWT认证\r\n- 1. 配置*/member*开头人路径不验证，将jwt串串存到header中：\r\n```go\r\n    hydra.Conf.API(\"8080\").Jwt(jwt.WithExcludes(\"/member/**\"), jwt.WithHeader())\r\n```\r\n- 2. 登录成功设置jwt信息:\r\n\r\n```go\r\ntype UserInfo struct{\r\n    Name string `json:\"name\"`\r\n    UID string `json:\"id\"`\r\n}\r\n\r\n\r\nfunc login(ctx hydra.IContext) interface{} {\r\n    userInfo := UserInfo{UID:\"209867923\",Name:\"colin\"}\r\n\tctx.User().Auth().Response(\u0026userInfo)\r\n\treturn \"success\"\r\n}\r\n\r\n```\r\n\r\n- 3. 从jwt中获取用户信息:\r\n```go\r\nfunc login(ctx hydra.IContext) interface{} {\r\n     userInfo :=new(UserInfo)\r\n\tctx.User().Auth().Bind(\u0026userInfo)\r\n\treturn \"success\"\r\n}\r\n```\r\n#### 7. 灰度发布\r\n\r\n以 *202.222.* 开头的IP，转发到名称中包含*gray*的集群（tengo脚本）:\r\n\r\n```go\r\n\thydra.Conf.API(\"8090\").Proxy(`\t\r\n                request := import(\"request\")\r\n                app := import(\"app\")\r\n                text := import(\"text\")\r\n                types :=import(\"types\")\r\n                fmt := import(\"fmt\")\r\n\r\n                getUpCluster := func(){\r\n                    ip := request.getClientIP()\r\n                    current:= app.getCurrentClusterName()\r\n                    if text.has_prefix(ip,\"202.222.\"){\r\n                        return app.getClusterNameBy(\"gray\")\r\n                    }\r\n                    return current\r\n                }\r\n                upcluster := getUpCluster()\r\n\t\t`)\r\n```\r\n#### 8. 自定义输出格式\r\n\r\n- 1. 处理输出（tengo脚本）：\r\n```go\r\n    hydra.Conf.API(\"8070\").Render(`\r\n            request := import(\"request\")\r\n            response := import(\"response\")\r\n            text := import(\"text\")\r\n            types :=import(\"types\")\r\n\r\n            rc:=\"\u003cresponse\u003e\u003ccode\u003e{@status}\u003c/code\u003e\u003cmsg\u003e{@content}\u003c/msg\u003e\u003c/response\u003e\"\r\n\r\n            getContent := func(){  \r\n                input:={status:response.getStatus(),content:response.getRaw()[\"id\"]}\r\n\r\n                if text.has_prefix(request.getPath(),\"/tx/request\"){\r\n                    return [200,types.translate(rc,input)]\r\n                }\r\n                if text.has_prefix(request.getPath(),\"/tx/query\"){\r\n                    return [200,types.translate(rc,input),\"text/plain\"]\r\n                }\r\n                return [200,response.getContent()]\r\n            }\r\n\r\n            render := getContent()\r\n            `)\r\n```\r\n\r\n- 2. 服务实现\r\n```go\r\nfunc main() {\r\n\tapp := hydra.NewApp(\r\n\t\thydra.WithServerTypes(http.API),\r\n\t)\r\n\r\n\tapp.API(\"/tx/request\", request)\r\n\tapp.API(\"/tx/query\", request)\r\n\tapp.API(\"/request\", request)\r\n\tapp.Start()\r\n}\r\nfunc request(ctx hydra.IContext) interface{} {\r\n\treturn map[string]interface{}{\r\n\t\t\"id\": 101010,\r\n\t}\r\n}\r\n```\r\n\r\n- 3. 请求服务\r\n```sh\r\n~/work/bin$ curl http://localhost:8070/tx/request\r\n\u003cresponse\u003e\u003ccode\u003e200\u003c/code\u003e\u003cmsg\u003e101010\u003c/msg\u003e\u003c/response\u003e\r\n\r\n~/work/bin$ curl http://localhost:8070/request\r\n{\"id\":101010}\r\n```\r\n\r\n#### 9. 数据库配置\r\n```go\r\n hydra.Conf.Vars().DB(\"db\", oracle.New(\"hydra/hydra\"))\r\n```\r\n\r\n使用方法:\r\n\r\n```go\r\n func GetUserInfo(id int64)(map[string]interface{},error)\r\n    db:=hydra.C.GetDB()\r\n    userInfo,err:=db.Query(\"select t.* from user_info t where t.id=@id\",map[string]interface{}{\"id\",id})\r\n    return userInfo,err\r\n```\r\n\r\n#### 10. 缓存配置\r\n```go\r\n hydra.Conf.Vars().Cache(\"cache\", redis.New(\"192.168.0.109\"))\r\n```\r\n\r\n使用方法:\r\n\r\n```go\r\n func GetUserInfo(id int64)(string,error)\r\n    cache:=hydra.C.GetCache()\r\n    userInfo,err:=cache.Get(fmt.Sprintf(\"user:info:%d\",id))\r\n    return userInfo,err\r\n```\r\n\r\n## 四、 服务注册\r\n\r\n- 1. 服务函数\r\n```go\r\nfunc main() {\r\n\tapp := hydra.NewApp(\r\n\t\thydra.WithServerTypes(http.API),\r\n\t)\r\n\tapp.API(\"/request\", request)\r\n\tapp.Start()\r\n}\r\nfunc request(ctx hydra.IContext) interface{} {\r\n\treturn \"success\"\r\n}\r\n```\r\n\r\n- 2. 包含Handle服务的struct构造函数或对象\r\n\r\n```go\r\nfunc main() {\r\n\tapp := hydra.NewApp(\r\n\t\thydra.WithServerTypes(http.API),\r\n\t)\r\n    app.API(\"/order\", NewOrderService)\r\n    //或\r\n    // app.API(\"/order\", \u0026OrderService{})\r\n\tapp.Start()\r\n}\r\n\r\ntype OrderService struct {\r\n}\r\nfunc NewOrderService()*OrderService{\r\n    return \u0026OrderService{}\r\n}\r\n\r\nfunc (o *OrderService) Handle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------订单处理----------\"))\r\n\treturn \"success\"\r\n}\r\n```\r\n\r\n- 3. 多个服务注册\r\n\r\n```go\r\nfunc main() {\r\n\tapp := hydra.NewApp(\r\n\t\thydra.WithServerTypes(http.API),\r\n\t)\r\n\tapp.API(\"/order/*\", NewOrderService)\r\n\tapp.Start()\r\n}\r\n\r\ntype OrderService struct {\r\n}\r\nfunc NewOrderService()*OrderService{\r\n    return \u0026OrderService{}\r\n}\r\n\r\nfunc (o *OrderService) RequestHandle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------收单处理----------\"))\r\n\treturn \"success\"\r\n}\r\nfunc (o *OrderService) QueryHandle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------查单处理----------\"))\r\n\treturn \"success\"\r\n}\r\n```\r\n\u003e 实际注册了两个服务 */order/request*,*/order/query*\r\n\r\n\r\n- 3. RESTful服务注册\r\n\r\n```go\r\nfunc main() {\r\n\tapp := hydra.NewApp(\r\n\t\thydra.WithServerTypes(http.API),\r\n\t)\r\n\tapp.API(\"/product\", \u0026ProductService{})\r\n\tapp.Start()\r\n}\r\n\r\ntype ProductService struct {\r\n}\r\n\r\n\r\n\r\nfunc (o *ProductService) GetHandle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------查询产品----------\"))\r\n\treturn \"success\"\r\n}\r\nfunc (o *ProductService) PostHandle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------新增产品----------\"))\r\n\treturn \"success\"\r\n}\r\nfunc (o *OrderService) PutHandle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------修改产品----------\"))\r\n\treturn \"success\"\r\n}\r\nfunc (o *OrderService) DeleteHandle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------禁用产品----------\"))\r\n\treturn \"success\"\r\n}\r\n```\r\n\r\n\u003e 实际注册了一个服务 */product*\r\n\r\n\r\n\r\n- 4. 钩子函数\r\n\r\n```go\r\nfunc main() {\r\n\tapp := hydra.NewApp(\r\n\t\thydra.WithServerTypes(http.API),\r\n\t)\r\n    app.API(\"/order\", NewOrderService)\r\n\tapp.Start()\r\n}\r\n\r\ntype OrderService struct {\r\n}\r\nfunc NewOrderService()*OrderService{\r\n    return \u0026OrderService{}\r\n}\r\nfunc (o *OrderService) Handling(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------预处理----------\"))\r\n\treturn \"success\"\r\n}\r\nfunc (o *OrderService) Handle(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------订单处理----------\"))\r\n\treturn \"success\"\r\n}\r\nfunc (o *OrderService) Handled(ctx hydra.IContext) interface{} {\r\n\tctx.Log().Info(\"--------后处理----------\"))\r\n\treturn \"success\"\r\n}\r\n\r\n```\r\n## 五、 服务响应\r\n\r\n\r\n- 1. 普通字符串\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n\treturn \"success\"\r\n}\r\n```\r\n\r\n\u003e 响应内容: *success*  \r\n\u003e Content-Type: text/plain; charset=utf-8\r\n\r\n\r\n\r\n- 2. JSON字符串\r\n\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n\treturn `{\"name\":\"colin\"}`\r\n}\r\n```\r\n\r\n\u003e 响应内容: *{\"name\":\"colin\"}*  \r\n\u003e Content-Type: application/json; charset=utf-8\r\n\r\n\r\n- 3. XML字符串\r\n\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n\treturn `\u003cname\u003ecolin\u003c/name\u003e`\r\n}\r\n```\r\n\r\n\u003e 响应内容: \u0026#60;name\u0026#62; colin\u0026#60;/name\u0026#62; \r\n\u003e Content-Type: application/xml; charset=utf-8\r\n\r\n\r\n- 4. Map\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n\treturn map[string]interface{}{\"name\":\"colin\"}\r\n}\r\n```\r\n\u003e 响应内容: *{\"name\":\"colin\"}*  \r\n\u003e Content-Type: application/json; charset=utf-8\r\n\r\n- 5. Struct\r\n\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n\treturn \u0026UserInfo{Name:\"colin\"}\r\n}\r\n```\r\n\r\n\u003e 响应内容: *{\"name\":\"colin\"}*  \r\n\u003e Content-Type: application/json; charset=utf-8\r\n\r\n\r\n- 6. Map,指定ContentType\r\n\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n    ctx.Response().ContentType(context.UTF8XML)\r\n\treturn map[string]interface{}{\"name\":\"colin\"}\r\n}\r\n```\r\n\r\n\u003e 响应内容:  *\u0026#60;name/\u0026#62;colin \u0026#60;name/\u0026#62;*\r\n\u003e Content-Type: application/xml; charset=utf-8\r\n\r\n\r\n- 7. Struct,指定ContentType\r\n\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n    ctx.Response().ContentType(context.UTF8XML)\r\n\treturn \u0026UserInfo{Name:\"colin\"}\r\n}\r\n```\r\n\r\n\u003e 响应内容: *\u0026#60;name/\u0026#62;colin \u0026#60;name/\u0026#62;*\r\n\u003e Content-Type: application/xml; charset=utf-8\r\n\r\n- 8. 普通错误\r\n\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n   return fmt.Errorf(\"err\")\r\n}\r\n```\r\n\r\n\u003e 响应内容: err\r\n\u003e Content-Type: text/plain; charset=utf-8\r\n\r\n- 9. 带状态码的错误\r\n\r\n```go\r\nfunc request(ctx hydra.IContext) interface{} {\r\n   return errs.New(500,\"err\")\r\n}\r\n```\r\n\r\n\u003e 状态码: 500\r\n\u003e 响应内容: err\r\n\u003e Content-Type: text/plain; charset=utf-8\r\n\r\n\r\n\r\n### 🐿️联系作者\r\n![image](https://github.com/micro-plat/hydra/raw/master/imgs/wx-p.png)\r\n\r\n### 💲捐赠 🥣\r\n![image](https://github.com/micro-plat/hydra/raw/master/imgs/jz.png)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicro-plat%2Fhydra","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmicro-plat%2Fhydra","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicro-plat%2Fhydra/lists"}