• Stars
    star
    551
  • Rank 80,726 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created about 8 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A lightweight, composable and high performance web service framework for Go.

Gear

CI Codecov CodeQL Go Reference License

A lightweight, composable and high performance web service framework for Go.

Features

  • Effective and flexible middlewares flow control, create anything by middleware
  • Powerful and smart HTTP error handling
  • Trie base gear.Router, as faster as HttpRouter, support regexp parameters and group routes
  • Integrated timeout context.Context
  • Integrated response content compress
  • Integrated structured logging middleware
  • Integrated request body parser
  • Integrated signed cookies
  • Integrated JSON, JSONP, XML and HTML renderer
  • Integrated CORS, Secure, Favicon and Static middlewares
  • More useful methods on gear.Context to manipulate HTTP Request/Response
  • Run HTTP and gRPC on the same port
  • Completely HTTP/2.0 supported

Documentation

Go-Documentation

Import

// package gear
import "github.com/teambition/gear"

Design

  1. Server 底层基于原生 net/http 而不是 fasthttp
  2. 通过 gear.Middleware 中间件模式扩展功能模块
  3. 中间件的单向顺序流程控制和级联流程控制
  4. 功能强大,完美集成 context.Context 的 gear.Context
  5. 集中、智能、可自定义的错误和异常处理
  6. After Hook 和 End Hook 的后置处理
  7. Any interface 无限的 gear.Context 状态扩展能力
  8. 请求数据的解析和验证

FAQ

  1. 如何从源码自动生成 Swagger v2 的文档?
  2. Go 语言完整的应用项目结构最佳实践是怎样的?

Demo

Hello

https://github.com/teambition/gear/tree/master/example/hello

  app := gear.New()

  // Add logging middleware
  app.UseHandler(logging.Default(true))

  // Add router middleware
  router := gear.NewRouter()

  // try: http://127.0.0.1:3000/hello
  router.Get("/hello", func(ctx *gear.Context) error {
    return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
  })

  // try: http://127.0.0.1:3000/test?query=hello
  router.Otherwise(func(ctx *gear.Context) error {
    return ctx.JSON(200, map[string]any{
      "Host":    ctx.Host,
      "Method":  ctx.Method,
      "Path":    ctx.Path,
      "URI":     ctx.Req.RequestURI,
      "Headers": ctx.Req.Header,
    })
  })
  app.UseHandler(router)
  app.Error(app.Listen(":3000"))

HTTP2 with Push

https://github.com/teambition/gear/tree/master/example/http2

package main

import (
  "net/http"

  "github.com/teambition/gear"
  "github.com/teambition/gear/logging"
  "github.com/teambition/gear/middleware/favicon"
)

// go run example/http2/app.go
// Visit: https://127.0.0.1:3000/
func main() {
  const htmlBody = `
<!DOCTYPE html>
<html>
  <head>
    <link href="/hello.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <h1>Hello, Gear!</h1>
  </body>
</html>`

  const pushBody = `
h1 {
  color: red;
}
`

  app := gear.New()

  app.UseHandler(logging.Default(true))
  app.Use(favicon.New("./testdata/favicon.ico"))

  router := gear.NewRouter()
  router.Get("/", func(ctx *gear.Context) error {
    ctx.Res.Push("/hello.css", &http.PushOptions{Method: "GET"})
    return ctx.HTML(200, htmlBody)
  })
  router.Get("/hello.css", func(ctx *gear.Context) error {
    ctx.Type("text/css")
    return ctx.End(200, []byte(pushBody))
  })
  app.UseHandler(router)
  app.Error(app.ListenTLS(":3000", "./testdata/out/test.crt", "./testdata/out/test.key"))
}

A CMD tool: static server

https://github.com/teambition/gear/tree/master/example/staticgo

Install it with go:

go install github.com/teambition/gear/example/staticgo@latest

It is a useful CMD tool that serve your local files as web server (support TLS). You can build osx, linux, windows version with make build.

package main

import (
  "flag"

  "github.com/teambition/gear"
  "github.com/teambition/gear/logging"
  "github.com/teambition/gear/middleware/cors"
  "github.com/teambition/gear/middleware/static"
)

var (
  address  = flag.String("addr", "127.0.0.1:3000", `address to listen on.`)
  path     = flag.String("path", "./", `static files path to serve.`)
  certFile = flag.String("certFile", "", `certFile path, used to create TLS static server.`)
  keyFile  = flag.String("keyFile", "", `keyFile path, used to create TLS static server.`)
)

func main() {
  flag.Parse()
  app := gear.New()

  app.UseHandler(logging.Default(true))
  app.Use(cors.New())
  app.Use(static.New(static.Options{Root: *path}))

  logging.Println("staticgo v1.2.0, created by https://github.com/teambition/gear")
  logging.Printf("listen: %s, serve: %s\n", *address, *path)

  if *certFile != "" && *keyFile != "" {
    app.Error(app.ListenTLS(*address, *certFile, *keyFile))
  } else {
    app.Error(app.Listen(*address))
  }
}

A CMD tool: reverse proxy server

https://github.com/teambition/gear/tree/master/example/gearproxy

Install it with go:

go install github.com/teambition/gear/example/gearproxy@latest
gearproxy -help

HTTP2 & gRPC

https://github.com/teambition/gear/tree/master/example/grpc_server

https://github.com/teambition/gear/tree/master/example/grpc_client

About Router

gear.Router is a trie base HTTP request handler. Features:

  1. Support named parameter
  2. Support regexp
  3. Support suffix matching
  4. Support multi-router
  5. Support router layer middlewares
  6. Support fixed path automatic redirection
  7. Support trailing slash automatic redirection
  8. Automatic handle 405 Method Not Allowed
  9. Automatic handle OPTIONS method
  10. Best Performance

The registered path, against which the router matches incoming requests, can contain six types of parameters:

Syntax Description
:name named parameter
:name(regexp) named with regexp parameter
:name+suffix named parameter with suffix matching
:name(regexp)+suffix named with regexp parameter and suffix matching
:name* named with catch-all parameter
::name not named parameter, it is literal :name

Named parameters are dynamic path segments. They match anything until the next '/' or the path end:

Defined: /api/:type/:ID

/api/user/123             matched: type="user", ID="123"
/api/user                 no match
/api/user/123/comments    no match

Named with regexp parameters match anything using regexp until the next '/' or the path end:

Defined: /api/:type/:ID(^\d+$)

/api/user/123             matched: type="user", ID="123"
/api/user                 no match
/api/user/abc             no match
/api/user/123/comments    no match

Named parameters with suffix, such as Google API Design:

Defined: /api/:resource/:ID+:undelete

/api/file/123                     no match
/api/file/123:undelete            matched: resource="file", ID="123"
/api/file/123:undelete/comments   no match

Named with regexp parameters and suffix:

Defined: /api/:resource/:ID(^\d+$)+:cancel

/api/task/123                   no match
/api/task/123:cancel            matched: resource="task", ID="123"
/api/task/abc:cancel            no match

Named with catch-all parameters match anything until the path end, including the directory index (the '/' before the catch-all). Since they match anything until the end, catch-all parameters must always be the final path element.

Defined: /files/:filepath*

/files                           no match
/files/LICENSE                   matched: filepath="LICENSE"
/files/templates/article.html    matched: filepath="templates/article.html"

The value of parameters is saved on the Matched.Params. Retrieve the value of a parameter by name:

type := matched.Params("type")
id   := matched.Params("ID")

More Middlewares

License

Gear is licensed under the MIT license. Copyright © 2016-2023 Teambition.

More Repositories

1

then.js

[快照]史上最快,与 node callback 完美结合的异步流程控制库!
JavaScript
573
star
2

teambition-sdk

Isomorphic JavaScript SDK for Teambition APIs
TypeScript
433
star
3

rrule-go

Go library for working with recurrence rules for calendar dates.
Go
313
star
4

TBEmptyDataSet

An extension of UITableView/UICollectionView's super class, it will display a placeholder emptyDataSet when the data of tableView/collectionView is empty.
Swift
206
star
5

Hire

Working With Great People
200
star
6

gulp-sequence

Run a series of gulp tasks in order
JavaScript
195
star
7

gulp-ssh

SSH and SFTP tasks for gulp
JavaScript
183
star
8

merge2

Merge multiple streams into one stream in sequence or parallel (~119M/month downloads).
JavaScript
171
star
9

DropdownMenu

Dropdown menu for NavigationController in Swift, also support Dropup Menu
Swift
133
star
10

snapper-core

Teambition push messaging service, backed by redis.
JavaScript
115
star
11

webapp-solutions

Try to collect anwsers on problems we encounter in Web Apps
113
star
12

ReactiveDB

Reactive ORM for Lovefield
TypeScript
105
star
13

jsonrpc-lite

Parse and Serialize JSON-RPC2 messages in node.js, or browser.
JavaScript
95
star
14

ratelimiter-go

The fastest abstract rate limiter, base on go-redis/redis.
Go
93
star
15

RRuleSwift

Swift rrule library for working with recurrence rules of calendar dates.
JavaScript
90
star
16

swaggo

Convert Go annotations to Swagger Documentation (version 2.0)
Go
68
star
17

SegmentedControl

A highly customizable segmented control for iOS applications.
Swift
64
star
18

HanziPinyin

A lightweight Swift library supporting convertion between Chinese(both Simplified and Tranditional) characters and Pinyin.
Swift
57
star
19

WebBrowser

A web browser using WebKit and written in Swift for iOS apps.
Swift
55
star
20

timed-queue

Distributed timed job queue, backed by Redis.
JavaScript
50
star
21

pdfviewer

PDF Viewer using Mozilla PDF JS
JavaScript
49
star
22

AMRAudioSwift

A useful tool to encode or decode audio between AMR and WAVE.
Swift
38
star
23

CardStyleTableView

An extension of UITableView and UITableViewCell which displays a card style view in grouped tableView, similar to the system's tableView before iOS 7.
Swift
32
star
24

trie-mux

A minimal and powerful trie based url path router (or mux) for Go.
Go
27
star
25

Pocket-Node-SDK

Headless Node.js SDK for integrating with [Pocket](http://getpocket.com/)
CoffeeScript
23
star
26

TB-Icons

A classified icons set that consists of a part of Material Design icons and some original icons by TB-UI team. Available in Icon Fonts and SVG Symbols.
Stylus
23
star
27

limbo

Factory/Loader of mongoose
CoffeeScript
17
star
28

json-mask-go

👺 JSON mask for Go
Go
10
star
29

tb-i18n-loader

i18n loader of teambition web for webpack
JavaScript
9
star
30

tws-auth

Node.js SDK of TWS (Teambition Web Service) client.
TypeScript
8
star
31

snapper-swift

Snapper-core client by Swift 2.0
Swift
8
star
32

node-teambition

JavaScript
7
star
33

redlimit

RedLimit is a redis-based distributed rate limit HTTP service, implemented with Rust.
Rust
7
star
34

tb-apps-sdk

Teambition API Bridge
TypeScript
7
star
35

teambition-node-sdk

teambition node sdk for server applications
TypeScript
6
star
36

WeChatSDK

Swift version of WeChat SDK.
Objective-C
5
star
37

node-chinese-finance-number

JavaScript
4
star
38

smart-limiter

Smart rate limiter middleware for express.
JavaScript
4
star
39

urbs-setting

Urbs 灰度平台灰度策略服务
Go
4
star
40

ilog

light-weight, smart and pure log module
JavaScript
3
star
41

teambition-java-sdk

teambition java sdk for server applications
Java
3
star
42

pipe-errors

Handle errors on piping streams and pipe error to the end.
JavaScript
3
star
43

i18n-middleware

An i18n middleware built for web apps.
CoffeeScript
2
star
44

grpclb

grpclb policy that consistent hash implemention, base on discovery systems like etcd, consul etc.
Go
2
star
45

teambition-server-sdk

TypeScript
2
star
46

gem-next

general entity manager next generation
TypeScript
2
star
47

tws-tcm

Node.js SDK of TWS (Teambition Web Service) cloud messaging service
TypeScript
1
star