{"id":26886226,"url":"https://github.com/coajs/coa-http","last_synced_at":"2025-05-08T23:11:33.829Z","repository":{"id":37083646,"uuid":"266057000","full_name":"coajs/coa-http","owner":"coajs","description":"🍀 A simple, fast, lightweight http service framework, is born for the API.","archived":false,"fork":false,"pushed_at":"2023-07-19T02:26:33.000Z","size":222,"stargazers_count":5,"open_issues_count":6,"forks_count":5,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-05-02T19:43:12.820Z","etag":null,"topics":["coa","coa-http","coajs","http","koa"],"latest_commit_sha":null,"homepage":"https://npmjs.com/coa-http","language":"TypeScript","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/coajs.png","metadata":{"files":{"readme":"README.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,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-05-22T08:19:25.000Z","updated_at":"2025-03-21T07:45:44.000Z","dependencies_parsed_at":"2024-11-14T16:50:33.909Z","dependency_job_id":null,"html_url":"https://github.com/coajs/coa-http","commit_stats":{"total_commits":55,"total_committers":5,"mean_commits":11.0,"dds":0.1636363636363637,"last_synced_commit":"a77e02aee107996b99b9fc8d0295e47c4a7140b4"},"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-http","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-http/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-http/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coajs%2Fcoa-http/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/coajs","download_url":"https://codeload.github.com/coajs/coa-http/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253160777,"owners_count":21863631,"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":["coa","coa-http","coajs","http","koa"],"created_at":"2025-03-31T19:17:37.284Z","updated_at":"2025-05-08T23:11:33.794Z","avatar_url":"https://github.com/coajs.png","language":"TypeScript","readme":"# coa-http\n\n[![GitHub license](https://img.shields.io/badge/license-MIT-green.svg?style=flat-square)](LICENSE)\n[![npm version](https://img.shields.io/npm/v/coa-http.svg?style=flat-square)](https://www.npmjs.org/package/coa-http)\n[![npm downloads](https://img.shields.io/npm/dm/coa-http.svg?style=flat-square)](http://npm-stat.com/charts.html?package=coa-http)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/coajs/coa-http/pulls)\n\nEnglish | [简体中文](README.zh-CN.md)\n\nA simple, fast, lightweight HTTP service frame, is born for the API.\n\n## Feature\n\n- **For the API** Designed for API development, there is no need to consider complex page data rendering logic\n- **Lightweight** Less than 10K, do not rely on third-party libraries, not encapsulation\n- **Flexible** Support micro-service, Serverless mode, Context free expansion\n- **Document friendship** Automatically generate API documents, automatically generate front-end code\n- **TypeScript** All written in TypeScript, type constraint, IDE friendship\n- **Deno** Can be supported in Deno (todo)\n\n## Reference\n\n- Inspired by [koa](https://www.npmjs.com/package/koa), improve the context generation mechanism\n- Inspired by [koa-router](https://www.npmjs.com/package/koa-router), improve the routing generation mechanism\n- Inspired by [koa-bodyparser](https://www.npmjs.com/package/koa-bodyparser), improve the request body processing mechanism\n- Inspired by [egg](https://eggjs.org/zh-cn), improve the context expansion mechanism\n- Based on [swagger-ui](https://swagger.io/tools/swagger-ui), complete the automatic generation of interface documents\n\n## Iteration\n\n- The first version [coajs](https://www.npmjs.com/package/coajs): The first version released in 2019, it belongs to the integration of third-party libraries. From multiple online projects, it is easy to deploy updates as a separate library. With the continuous iteration, there is more and more things, `coajs` becomes more bloated, is not suitable for lightweight small projects. Iterate 114 times after stop maintenance\n\n- Second version [coa-serve](https://www.npmjs.com/package/coa-serve): For the bloated problem of the first release, the various components are split based on `coajs`, separate the base components and core components into separate libraries, and **open source**. At the same time, there is a lot of optimization for document generation mechanisms, routing retrieval, system environment configuration. Currently stable, all of my online `coajs` projects have been migrated to `coa-server`\n\n- Third version [coa-http](https://www.npmjs.com/package/coa-http): The current version. With the continuous iteration, the way the interface provides service is not limited to `http`, integrate `tcp`, `websocket`, etc. Direct to `coa-serve` is not elegant. In addition, ~~As the author's cognitive progress~~, `koa` ecosystem is not the best choice. Therefore, it is planned to disassemble the `coa-serve` to reconfigure to [coa-http](https://www.npmjs.com/package/coa-http), [coa-tcp](https://www.npmjs.com/package/coa-tcp), [coa-websocket](https://www.npmjs.com/package/coa-websocket), etc. This project `coa-http` is one of these three, still in the beta stage\n\n## Quick Start\n\n### Environmental install\n\nMake sure that the latest stable version of [Node.js](https://nodejs.org) is installed on the operating system\n\n### Create a project\n\n```shell\nmkdir \u003cproject-name\u003e\ncd \u003cproject-name\u003e\n\nyarn add coa-http\nyarn add typescript tsc-watch @types/node -D\n```\n\n### Create files\n\n```shell\ngateway            # Gateway layer\n├─ index.ts        # Gateway entrance\n├─ debug           # debug module\n│  └─ test.ts      # The route of the debug module\nservice            # Service layer\n├─ index.ts        # Implement service\npackage.json\ntsconfig.json\n```\n\nWrite the code in `gateway/index.ts`\n\n```typescript\nimport { CoaContext, CoaHttp } from 'coa-http'\n\nexport const http = new CoaHttp(CoaContext)\n\nhttp.start().then(() =\u003e {\n  // Do something after starting\n})\n```\n\nWrite the code in `gateway/debug/test.ts`\n\n```typescript\nimport { http } from '..'\n\nhttp.router.register('Debug Something', {\n  '/debug/test/hello': {\n    options: {\n      method: 'GET',\n      name: 'Hello, world',\n    },\n    async handler() {\n      return { result: 'hello,world!' }\n    },\n  },\n})\n```\n\nWrite configuration in `tsconfig.json`\n\n```json\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"module\": \"CommonJS\",\n    \"target\": \"ESNext\",\n    \"baseUrl\": \".\",\n    \"outDir\": \"node_run\",\n    \"sourceMap\": true\n  },\n  \"include\": [\"gateway\", \"service\"]\n}\n```\n\nAdd `dev` script of `script` node in `package.json`\n\n```json\n{\n  \"scripts\": {\n    \"dev\": \"HOST=3000 NODE_PATH=node_run tsc-watch --onSuccess 'node node_run/gateway'\"\n  }\n}\n```\n\n### Start up\n\n```shell\nyarn dev\n```\n\nSee something similar to the following operating results, indicating the success of the program starts. After modifying the code, it will automatically restart the service.\n\n```text\nFound 0 errors. Watching for file changes.\n[server] Booting...\n[server] Startup successful in: 5.399953 ms\n[server] Listening on: http://localhost:3000/gw/doc\n```\n\nAt this point, open the `http://localhost:3000/gw/doc`, you can directly view the interface document.\n\n## Route\n\n### Basic usage\n\nUse the `http.router.register` method to register the route, a simplest route as shown below.\n\n```typescript\nhttp.router.register('Debug Something', {\n  '/debug/test/hello': {\n    options: {\n      name: 'Test Something', // name\n      method: 'GET', // method\n      param: {\n        title: { required: true, description: 'Title parameters', example: 'test' },\n      },\n    },\n    async handler(ctx) {\n      // Get all query parameters\n      const query = ctx.request.query\n      // Get title parameters\n      const title2 = ctx.get('title')\n      // Return the result with JSON format\n      return { query, title }\n    },\n  },\n})\n```\n\n### Route group\n\nEach of the registered routes will be automatically divided into a group. When developing, you can split each module into a file separate grouping.\n\n```typescript\n// gateway/module-a.ts\nhttp.router.register('Module A', {\n  '/api/module-a/action-1': {\n    /* ... */\n  },\n  '/api/module-a/action-2': {\n    /* ... */\n  },\n})\n// gateway/module-b.ts\nhttp.router.register('Module B', {\n  '/api/module-b/action-1': {\n    /* ... */\n  },\n  '/api/module-b/action-2': {\n    /* ... */\n  },\n  '/api/module-b/action-3': {\n    /* ... */\n  },\n})\n```\n\n### Context\n\nSimilar to `koa`, `handler` method contains a `ctx` parameter. `ctx` is an instance of `Context` that contains all the above information during the current request.\n\n```typescript\nhttp.router.register('Debug Something', {\n  '/debug/test/hello': {\n    options: {\n      method: 'GET',\n      name: 'Hello, world',\n    },\n    async handler(ctx) {\n      // ctx contains all context information\n      return { result: 'hello, world!' }\n    },\n  },\n})\n```\n\n### Custom response format\n\n`coa-http` Natively supports the response results in `json` and `text` format. But sometimes we need to customize the response format, such as a stream format. The following example shows the returns of resources on the network through the stream.\n\n```typescript\nhttp.router.register('Debug Something', {\n  '/debug/test/proxy': {\n    options: {\n      method: 'GET',\n      name: 'Returns the result with stream',\n      param: {\n        url: { required: true, description: 'Network resource path', example: 'http://github.com' },\n      },\n    },\n    async handler(ctx) {\n      // Get url parameters\n      const url = ctx.required('url', '')\n\n      // Get resource streams on the network\n      const { data, status, headers } = await axios.get(url, { responseType: 'stream' }).catch((e) =\u003e e.response)\n\n      // Set response info\n      ctx.res.statusCode = status\n      ctx.res.setHeader('Content-Type', headers['content-type'])\n\n      // Resource flow on the network flows in the pipeline\n      data.pipe(ctx.res)\n\n      // Custom response results, coa-http will not perform subsequent response processing\n      return ctx.custom()\n    },\n  },\n})\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoajs%2Fcoa-http","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcoajs%2Fcoa-http","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoajs%2Fcoa-http/lists"}