{"id":18673050,"url":"https://github.com/vicanso/elton","last_synced_at":"2025-04-06T13:11:11.165Z","repository":{"id":44349212,"uuid":"159825326","full_name":"vicanso/elton","owner":"vicanso","description":"High performance, simple Go web framework","archived":false,"fork":false,"pushed_at":"2024-12-12T12:27:30.000Z","size":776,"stargazers_count":66,"open_issues_count":0,"forks_count":5,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-03-30T12:07:31.556Z","etag":null,"topics":["elton","go","golang","webframework"],"latest_commit_sha":null,"homepage":"https://treexie.gitbook.io/elton/","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/vicanso.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":"2018-11-30T13:10:48.000Z","updated_at":"2024-12-16T09:48:13.000Z","dependencies_parsed_at":"2024-02-09T02:29:52.681Z","dependency_job_id":"51271678-c670-42e5-ac5e-1398d24898c8","html_url":"https://github.com/vicanso/elton","commit_stats":null,"previous_names":["vicanso/cod"],"tags_count":86,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicanso%2Felton","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicanso%2Felton/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicanso%2Felton/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vicanso%2Felton/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vicanso","download_url":"https://codeload.github.com/vicanso/elton/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247485287,"owners_count":20946398,"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":["elton","go","golang","webframework"],"created_at":"2024-11-07T09:13:50.785Z","updated_at":"2025-04-06T13:11:11.149Z","avatar_url":"https://github.com/vicanso.png","language":"Go","readme":"# Elton \n\n[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/vicanso/elton/blob/master/LICENSE)\n[![Build Status](https://github.com/vicanso/elton/workflows/Test/badge.svg)](https://github.com/vicanso/elton/actions)\n\n![Alt](https://repobeats.axiom.co/api/embed/4f64b99db39c6a75b6980ebb3c756244b246a718.svg \"Repobeats analytics image\")\n\nElton的实现参考了[koa](https://github.com/koajs/koa)以及[echo](https://github.com/labstack/echo)，中间件的调用为洋葱模型：请求由外至内，响应由内至外。主要特性如下：\n\n- 处理函数（中间件）均以返回error的形式响应出错，方便使用统一的出错处理中间件将出错统一转换为对应的输出（JSON），并根据出错的类型等生成各类统计分析\n- 成功响应数据直接赋值至Context.Body（interface{})，由统一的响应中间件将其转换为对应的输出（JSON，XML）\n- 支持不同种类的事件，如`OnBefore`、`OnDone`、`OnError`等，方便添加各类统计行为\n\n如何使用`elton`开发WEB后端程序，可以参考[一步一步学习如何使用elton](https://treexie.gitbook.io/elton-beginner/)\n\n## Hello, World!\n\n下面我们来演示如何使用`elton`返回`Hello, World!`，并且添加了一些常用的中间件。\n\n```go\npackage main\n\nimport (\n\t\"github.com/vicanso/elton\"\n\t\"github.com/vicanso/elton/middleware\"\n)\n\nfunc main() {\n\te := elton.New()\n\n\t// panic处理\n\te.Use(middleware.NewRecover())\n\n\t// 出错处理\n\te.Use(middleware.NewDefaultError())\n\n\t// 默认的请求数据解析\n\te.Use(middleware.NewDefaultBodyParser())\n\n\t// not modified 304的处理\n\te.Use(middleware.NewDefaultFresh())\n\te.Use(middleware.NewDefaultETag())\n\n\t// 响应数据转换为json\n\te.Use(middleware.NewDefaultResponder())\n\n\te.GET(\"/\", func(c *elton.Context) error {\n\t\tc.Body = \u0026struct {\n\t\t\tMessage string `json:\"message,omitempty\"`\n\t\t}{\n\t\t\t\"Hello, World!\",\n\t\t}\n\t\treturn nil\n\t})\n\n\te.GET(\"/books/{id}\", func(c *elton.Context) error {\n\t\tc.Body = \u0026struct {\n\t\t\tID string `json:\"id,omitempty\"`\n\t\t}{\n\t\t\tc.Param(\"id\"),\n\t\t}\n\t\treturn nil\n\t})\n\n\te.POST(\"/login\", func(c *elton.Context) error {\n\t\tc.SetContentTypeByExt(\".json\")\n\t\tc.Body = c.RequestBody\n\t\treturn nil\n\t})\n\n\terr := e.ListenAndServe(\":3000\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n```\n\n```bash\ngo run main.go\n```\n\n之后在浏览器中打开`http://localhost:3000/`则能看到返回的`Hello, World!`。\n\n## 路由\n\nelton每个路由可以添加多个中间件处理函数，根据路由与及HTTP请求方法指定不同的路由处理函数。而全局的中间件则可通过`Use`方法来添加。\n\n```go\ne.Use(...func(*elton.Context) error)\ne.Method(path string, ...func(*elton.Context) error)\n```\n\n- `e` 为`elton`实例化对象\n- `Method` 为HTTP的请求方法，如：`GET`, `PUT`, `POST`等等\n- `path` 为HTTP路由路径\n- `func(*elton.Context) error` 为路由处理函数（中间件），当匹配的路由被请求时，对应的处理函数则会被调用\n\n### 路由示例\n\nelton的路由使用[chi](https://github.com/go-chi/chi)的路由简化而来，下面是两个简单的示例。\n\n```go\n// 带参数路由\ne.GET(\"/users/{type}\", func(c *elton.Context) error {\n\tc.BodyBuffer = bytes.NewBufferString(c.Param(\"type\"))\n\treturn nil\n})\n\n// 复合参数\ne.GET(\"/books/{category:[a-z-]+}-{type}\", func(c *elton.Context) error {\n\tc.BodyBuffer = bytes.NewBufferString(c.Param(\"category\") + c.Param(\"type\"))\n\treturn nil\n})\n\n// 带中间件的路由配置\ne.GET(\"/users/me\", func(c *elton.Context) error {\n\tc.Set(\"account\", \"tree.xie\")\n\treturn c.Next()\n}, func(c *elton.Context) error {\n\tc.BodyBuffer = bytes.NewBufferString(c.GetString(\"account\"))\n\treturn nil\n})\n```\n\n## 中间件\n\n简单方便的中间件机制，依赖各类定制的中间件，通过各类中间件的组合，方便快捷实现各类HTTP服务，简单介绍数据响应与出错处理的中间件。需要注意，elton中默认不会执行所有的中间件，每个中间件决定是否需要执行后续处理，如果需要则调用Next()函数，与gin不一样(gin默认为执行所有，若不希望执行后续的中间件，则调用Abort)。\n\n### responder\n\nHTTP请求响应数据时，需要将数据转换为Buffer返回，而在应用时响应数据一般为各类的struct或map等结构化数据，因此elton提供了Body(interface{})字段来保存这些数据，再使用自定义的中间件将数据转换为对应的字节数据，`elton-responder`提供了将struct(map)转换为json字节并设置对应的Content-Type，对于string([]byte)则直接输出。\n\n```go\npackage main\n\nimport (\n\t\"github.com/vicanso/elton\"\n\t\"github.com/vicanso/elton/middleware\"\n)\n\nfunc main() {\n\n\te := elton.New()\n\t// 对响应数据 c.Body 转换为相应的json响应\n\te.Use(middleware.NewDefaultResponder())\n\n\tgetSession := func(c *elton.Context) error {\n\t\tc.Set(\"account\", \"tree.xie\")\n\t\treturn c.Next()\n\t}\n\te.GET(\"/users/me\", getSession, func(c *elton.Context) (err error) {\n\t\tc.Body = \u0026struct {\n\t\t\tName string `json:\"name\"`\n\t\t\tType string `json:\"type\"`\n\t\t}{\n\t\t\tc.GetString(\"account\"),\n\t\t\t\"vip\",\n\t\t}\n\t\treturn\n\t})\n\n\terr := e.ListenAndServe(\":3000\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n```\n\n### error\n\n当请求处理失败时，直接返回error则可，elton从error中获取出错信息并输出。默认的出错处理并不适合实际应用场景，建议使用自定义出错类配合中间件，便于统一的错误处理，程序监控，下面是引入错误中间件将出错转换为json形式的响应。\n\n```go\npackage main\n\nimport (\n\t\"github.com/vicanso/elton\"\n\t\"github.com/vicanso/elton/middleware\"\n\t\"github.com/vicanso/hes\"\n)\n\nfunc main() {\n\n\te := elton.New()\n\t// 指定出错以json的形式返回\n\te.Use(middleware.NewError(middleware.ErrorConfig{\n\t\tResponseType: \"json\",\n\t}))\n\n\te.GET(\"/\", func(c *elton.Context) (err error) {\n\t\terr = \u0026hes.Error{\n\t\t\tStatusCode: 400,\n\t\t\tCategory:   \"users\",\n\t\t\tMessage:    \"出错啦\",\n\t\t}\n\t\treturn\n\t})\n\n\terr := e.ListenAndServe(\":3000\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n```\n\n更多的中间件可以参考[middlewares](./docs/middlewares.md)\n\n## bench\n\n```\ngoos: darwin\ngoarch: amd64\npkg: github.com/vicanso/elton\nBenchmarkRoutes-8                        6925746               169.4 ns/op           120 B/op          2 allocs/op\nBenchmarkGetFunctionName-8              136577900                9.265 ns/op           0 B/op          0 allocs/op\nBenchmarkContextGet-8                   15311328                78.11 ns/op           16 B/op          1 allocs/op\nBenchmarkContextNewMap-8                187684261                6.276 ns/op           0 B/op          0 allocs/op\nBenchmarkConvertServerTiming-8           1484379               835.8 ns/op           360 B/op         11 allocs/op\nBenchmarkGetStatus-8                    1000000000               0.2817 ns/op          0 B/op          0 allocs/op\nBenchmarkFresh-8                          955664              1233 ns/op             416 B/op         10 allocs/op\nBenchmarkStatic-8                          25128             46709 ns/op           20794 B/op        471 allocs/op\nBenchmarkGitHubAPI-8                       14724             76190 ns/op           27175 B/op        609 allocs/op\nBenchmarkGplusAPI-8                       326769              3659 ns/op            1717 B/op         39 allocs/op\nBenchmarkParseAPI-8                       162340              6989 ns/op            3435 B/op         78 allocs/op\nBenchmarkRWMutexSignedKeys-8            71757390                17.51 ns/op            0 B/op          0 allocs/op\nBenchmarkAtomicSignedKeys-8             923771157                1.297 ns/op           0 B/op          0 allocs/op\nPASS\nok      github.com/vicanso/elton        20.225s\ngoos: darwin\ngoarch: amd64\npkg: github.com/vicanso/elton/middleware\nBenchmarkGenETag-8                        230718              4409 ns/op             160 B/op          6 allocs/op\nBenchmarkMd5-8                            200134              5958 ns/op             120 B/op          6 allocs/op\nBenchmarkNewShortHTTPHeader-8           10220961               116.4 ns/op            80 B/op          2 allocs/op\nBenchmarkNewHTTPHeader-8                 4368654               277.1 ns/op            88 B/op          3 allocs/op\nBenchmarkNewHTTPHeaders-8                 384062              2822 ns/op            1182 B/op         23 allocs/op\nBenchmarkHTTPHeaderMarshal-8              225123              4664 ns/op            1344 B/op         21 allocs/op\nBenchmarkToHTTPHeader-8                   296210              3834 ns/op            1272 B/op         34 allocs/op\nBenchmarkHTTPHeaderUnmarshal-8            120136             10108 ns/op            1888 B/op         50 allocs/op\nBenchmarkProxy-8                           13393             85170 ns/op           16031 B/op        104 allocs/op\nPASS\nok      github.com/vicanso/elton/middleware     14.007s\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvicanso%2Felton","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvicanso%2Felton","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvicanso%2Felton/lists"}