golang的路由控制器框架chi

golang的路由控制器框架chi

官方介绍

chi is a lightweight, idiomatic and composable router for building Go 1.7+ HTTP services. It’s especially good at helping you write large REST API services that are kept maintainable as your project grows and changes. chi is built on the new context package introduced in Go 1.7 to handle signaling, cancelation and request-scoped values across a handler chain.

The focus of the project has been to seek out an elegant and comfortable design for writing REST API servers, written during the development of the Pressly API service that powers our public API service, which in turn powers all of our client-side applications.

The key considerations of chi’s design are: project structure, maintainability, standard http handlers (stdlib-only), developer productivity, and deconstructing a large system into many small parts. The core router github.com/go-chi/chi is quite small (less than 1000 LOC), but we’ve also included some useful/optional subpackages: middleware, render and docgen. We hope you enjoy it too!

翻译

  • Chi是一个轻量级的、惯用的、可组合的路由器,用于构建GO 1.7 + HTTP服务。它特别擅长帮助您编写大型REST API服务,这些服务在项目增长和更改时保持可维护性。chi构建在Go 1.7中引入的新上下文包之上,用于跨处理程序链处理信令、取消和请求范围值。

  • 该项目的重点是寻求一种优雅和舒适的设计来编写REST API服务器,该服务器是在Pressly API服务的开发过程中编写的,该服务为我们的公共API服务提供动力,而公共API服务又为我们的所有客户端应用程序提供动力。

  • Chi设计的主要考虑因素是:项目结构、可维护性、标准http处理程序(stdlib-only)、开发人员的生产力,以及将大型系统分解为许多小部件。核心路由器github.com/go-chi/chi非常小(小于1000LOC),但是我们也包括了一些有用的/可选的子包:中间件、呈现和docgen。我们希望你也喜欢它!

官方地址


### 如何安装

#### dep
```bash
dep ensure --add github.com/go-chi/chi

go

go get -u github.com/go-chi/chi

示例

hello world

package main

import (
    "net/http"
    "github.com/go-chi/chi"
)

func main() {
    r := chi.NewRouter()
    r.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hello world"))
    })
    http.ListenAndServe(":3000", r)
}

中间件的使用

中间件起承上启下的作用,所有它的实现需要一个context把中间件拿到的值,传递下去,
比如我们需要在request中做处理,那么我们需要调用r.WithContext(ctx),把request传递到server中,
同理,在response中我们仍需要response.WriteContext(ctx)

package main

import (
    "github.com/go-chi/chi"
    "net/http"
    "context"
    "log"
    "encoding/gob"
    "bytes"
)

func main() {
    r := chi.NewRouter()
    r.Use(MyMiddleWare)
    r.Get("/test", func(writer http.ResponseWriter, request *http.Request) {
        writer.Write([]byte("hello world\n"))
        writer.Write([]byte("hello world\n"))
        a := request.Context().Value("user")
        var buf bytes.Buffer
        enc := gob.NewEncoder(&buf)
        err := enc.Encode(a)
        if err != nil {
            log.Fatal(err)
        }
        //writer.Write([]byte(buf.Bytes()))
        log.Println(a)
    })
    http.ListenAndServe(":3000", r)
}


func MyMiddleWare(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := context.WithValue(r.Context(), "user", "123")
        log.Println("test")
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

核心中间件

允许访问的ContentType、是否压缩、获取请求头header、心跳、无缓存、真实ip等等,当然我们也可以扩展自己的中间件


chi/middleware Handler description
AllowContentType Explicit whitelist of accepted request Content-Types
Compress Gzip compression for clients that accept compressed responses
GetHead Automatically route undefined HEAD requests to GET handlers
Heartbeat Monitoring endpoint to check the servers pulse
Logger Logs the start and end of each request with the elapsed processing time
NoCache Sets response headers to prevent clients from caching
Profiler Easily attach net/http/pprof to your routers
RealIP Sets a http.Request’s RemoteAddr to either X-Forwarded-For or X-Real-IP
Recoverer Gracefully absorb panics and prints the stack trace
RequestID Injects a request ID into the context of each request
RedirectSlashes Redirect slashes on routing paths
SetHeader Short-hand middleware to set a response header key/value
StripSlashes Strip slashes on routing paths
Throttle Puts a ceiling on the number of concurrent requests
Timeout Signals to the request context when the timeout deadline is reached
URLFormat Parse extension from url and put it on request context
WithValue Short-hand middleware to set a key/value on the request context

路由器的设计

Each routing method accepts a URL pattern and chain of handlers

每个路由的设计都支持URL的正则匹配和chain话柄,如user/{userId},test/*等,
实例化一个chi的router r := chi.NewRouter()我们就可以实现开始我们的web后端api的开发了

引用

  1. https://www.sourcedev.cc/article/133

共 2 个回复


duanquanyong

我很喜欢这个路由,跟标准库结合都非常好。我所有都web项目用都都是这个

# 0