Ace-T's Blog 내 검색 [네이버 커넥트 이웃 합니다~^-^/ 요청 大 환영~~]

chi package

Language/go lang 2018.03.02 13:21
[Good Comment!!, Good Discussion!!, Good Contens!!]
[ If you think that is useful, please click the finger on the bottom~^-^good~ ]
by ace-T

HTTP Service를 구현할 때 사용한다.

Go 1.7이나 그 이상에서 사용이 가능하다.

package main

import (


func main() {
	r := chi.NewRouter()

	r.Get("/", func(w http.ResponseWriter, r *http.Request) {

	http.ListenAndServe(":3333", r)

여러가지 함수들이 다양하기 때문에 가지고 놀아봐야 제대로 알듯 하다.

chi package는 크게 Context, Middleware, Mux, Route 등으로 구성되어져있다고 보면 된다.

참고 :

그 중 Type Route은 아래와 같다.

Use : Mux middleware stack에 middleware handler를 추가 한다.   
        Mux를 위한 
middleware stack은 매칭을 검색하기 전에 실행 된다.
        특정 핸들러로 route하여 조기에 응답할 수 있는 기회를 제공 한다.
        그리고 요청 실행과정을 변경하거나 요청 범위 값을 다음 http.Handler를 위해 설정 합니다. 

// Use appends a middleware handler to the Mux middleware stack.
// The middleware stack for any Mux will execute before searching for a matching
// route to a specific handler, which provides opportunity to respond early,
// change the course of the request execution, or set request-scoped values for
// the next http.Handler.
func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler) {
if mx.handler != nil {
panic("chi: all middlewares must be defined before routes on a mux")
mx.middlewares = append(mx.middlewares, middlewares...)


// Middlewares type is a slice of standard middleware handlers with methods
// to compose middleware chains and http.Handler's.
type Middlewares []func(http.Handler) http.Handler

Route : 새로운 middleware stack이 있는 새로운 Mux를 만들고 Sub Router로 패턴을 따라 마운트 한다.

// Route creates a new Mux with a fresh middleware stack and mounts it
// along the `pattern` as a subrouter. Effectively, this is a short-hand
// call to Mount. See _examples/.
func (mx *Mux) Route(pattern string, fn func(r Router)) Router {
subRouter := NewRouter()
if fn != nil {
mx.Mount(pattern, subRouter)
return subRouter


// Mount attaches another http.Handler or chi Router as a subrouter along a routing
// path. It's very useful to split up a large API as many independent routers and
// compose them as a single service using Mount. See _examples/.
// Note that Mount() simply sets a wildcard along the `pattern` that will continue
// routing at the `handler`, which in most cases is another chi.Router. As a result,
// if you define two Mount() routes on the exact same pattern the mount will panic.
func (mx *Mux) Mount(pattern string, handler http.Handler) {

Handle : http method와 일치하는 'handler' http.Handler를 실행한다.

// Handle and HandleFunc adds routes for `pattern` that matches
// all HTTP methods.
Handle(pattern string, h http.Handler)
HandleFunc(pattern string, h http.HandlerFunc)

Handler > ServeHTTP

// A Handler responds to an HTTP request.
// ServeHTTP should write reply headers and data to the ResponseWriter
// and then return. Returning signals that the request is finished; it
// is not valid to use the ResponseWriter or read from the
// Request.Body after or concurrently with the completion of the
// ServeHTTP call.
// Depending on the HTTP client software, HTTP protocol version, and
// any intermediaries between the client and the Go server, it may not
// be possible to read from the Request.Body after writing to the
// ResponseWriter. Cautious handlers should read the Request.Body
// first, and then reply.
// Except for reading the body, handlers should not modify the
// provided Request.
// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
// that the effect of the panic was isolated to the active request.
// It recovers the panic, logs a stack trace to the server error log,
// and either closes the network connection or sends an HTTP/2
// RST_STREAM, depending on the HTTP protocol. To abort a handler so
// the client sees an interrupted response but the server doesn't log
// an error, panic with the value ErrAbortHandler.
type Handler interface {
ServeHTTP(ResponseWriter, *Request)


type Router interface {

    // Use appends one of more middlewares onto the Router stack.
    Use(middlewares ...func(http.Handler) http.Handler)

    // With adds inline middlewares for an endpoint handler.
    With(middlewares ...func(http.Handler) http.Handler) Router

    // Group adds a new inline-Router along the current routing
    // path, with a fresh middleware stack for the inline-Router.
    Group(fn func(r Router)) Router

    // Route mounts a sub-Router along a `pattern`` string.
    Route(pattern string, fn func(r Router)) Router

    // Mount attaches another http.Handler along ./pattern/*
    Mount(pattern string, h http.Handler)

    // Handle and HandleFunc adds routes for `pattern` that matches
    // all HTTP methods.
    Handle(pattern string, h http.Handler)
    HandleFunc(pattern string, h http.HandlerFunc)

    // Method and MethodFunc adds routes for `pattern` that matches
    // the `method` HTTP method.
    Method(method, pattern string, h http.Handler)
    MethodFunc(method, pattern string, h http.HandlerFunc)

    // HTTP-method routing along `pattern`
    Connect(pattern string, h http.HandlerFunc)
    Delete(pattern string, h http.HandlerFunc)
    Get(pattern string, h http.HandlerFunc)
    Head(pattern string, h http.HandlerFunc)
    Options(pattern string, h http.HandlerFunc)
    Patch(pattern string, h http.HandlerFunc)
    Post(pattern string, h http.HandlerFunc)
    Put(pattern string, h http.HandlerFunc)
    Trace(pattern string, h http.HandlerFunc)

    // NotFound defines a handler to respond whenever a route could
    // not be found.
    NotFound(h http.HandlerFunc)

    // MethodNotAllowed defines a handler to respond whenever a method is
    // not allowed.
    MethodNotAllowed(h http.HandlerFunc)

'Language > go lang' 카테고리의 다른 글

기초) golang project 만들어보기!  (0) 2018.03.05
golang setting  (0) 2018.03.02
chi package  (0) 2018.03.02
go lang song? zz  (0) 2018.02.20
golang factory  (0) 2018.02.13
golang - Package json  (0) 2018.02.09

acet 박태하가 추천하는 readtrend 추천글!




:::: facebook을 이용하시는 분들은 로그인 후 아래에 코멘트를 남겨주세요 ::::

티스토리 툴바