本文整理匯總了Golang中github.com/pressly/chi.NewRouter函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewRouter函數的具體用法?Golang NewRouter怎麽用?Golang NewRouter使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewRouter函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestThrottleClientTimeout
func TestThrottleClientTimeout(t *testing.T) {
r := chi.NewRouter()
r.Use(ThrottleBacklog(10, 50, time.Second*10))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
time.Sleep(time.Second * 5) // Expensive operation.
w.Write(testContent)
})
server := httptest.NewServer(r)
client := http.Client{
Timeout: time.Second * 3, // Maximum waiting time.
}
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
_, err := client.Get(server.URL)
assert.Error(t, err)
}(i)
}
wg.Wait()
server.Close()
}
示例2: main
func main() {
// Setup the logger
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{} // optional / configurable, see docs
// Routes
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(NewStructuredLogger(logger))
r.Use(middleware.Recoverer)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("welcome"))
})
r.Get("/wait", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second)
LogEntrySetField(r, "wait", true)
w.Write([]byte("hi"))
})
r.Get("/panic", func(w http.ResponseWriter, r *http.Request) {
panic("oops")
})
http.ListenAndServe(":3333", r)
}
示例3: TestSimple
func TestSimple(t *testing.T) {
r := chi.NewRouter()
r.Use(TokenAuth.Verifier, jwtauth.Authenticator)
r.Get("/", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("welcome"))
})
ts := httptest.NewServer(r)
defer ts.Close()
// sending unauthorized requests
if status, resp := testRequest(t, ts, "GET", "/", nil, nil); status != 401 && resp != "Unauthorized\n" {
t.Fatalf(resp)
}
h := http.Header{}
h.Set("Authorization", "BEARER "+newJwtToken([]byte("wrong"), map[string]interface{}{}))
if status, resp := testRequest(t, ts, "GET", "/", h, nil); status != 401 && resp != "Unauthorized\n" {
t.Fatalf(resp)
}
h.Set("Authorization", "BEARER asdf")
if status, resp := testRequest(t, ts, "GET", "/", h, nil); status != 401 && resp != "Unauthorized\n" {
t.Fatalf(resp)
}
// sending authorized requests
if status, resp := testRequest(t, ts, "GET", "/", newAuthHeader(), nil); status != 200 && resp != "welcome" {
t.Fatalf(resp)
}
}
示例4: accountsRouter
func accountsRouter() chi.Router {
r := chi.NewRouter()
r.Use(sup1)
r.Get("/", listAccounts)
r.Post("/", createAccount)
r.Get("/hi", hiAccounts)
r.Group(func(r chi.Router) {
r.Use(sup2)
r.Get("/hi2", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
v := ctx.Value("sup2").(string)
w.Write([]byte(fmt.Sprintf("hi2 - '%s'", v)))
})
})
r.Route("/:accountID", func(r chi.Router) {
r.Use(accountCtx)
r.Get("/", getAccount)
r.Put("/", updateAccount)
r.Get("/*", other)
})
return r
}
示例5: router
func router() http.Handler {
r := chi.NewRouter()
// Protected routes
r.Group(func(r chi.Router) {
// Seek, verify and validate JWT tokens
r.Use(TokenAuth.Verifier)
// Handle valid / invalid tokens. In this example, we use
// the provided authenticator middleware, but you can write your
// own very easily, look at the Authenticator method in jwtauth.go
// and tweak it, its not scary.
r.Use(jwtauth.Authenticator)
r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
token := ctx.Value("jwt").(*jwt.Token)
claims := token.Claims
w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["user_id"])))
})
})
// Public routes
r.Group(func(r chi.Router) {
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("welcome anonymous"))
})
})
return r
}
示例6: New
// New returns a new blank Engine instance with no middleware attached
func New(opts Options) *Engine {
namespace := opts.Namespace
if len(namespace) == 0 {
namespace = "/"
}
engine := &Engine{}
engine.Router = &Router{
namespace: namespace,
engine: engine,
mux: chi.NewRouter(),
}
engine.options = opts
engine.pool.New = func() interface{} {
ctx := &Context{
Engine: engine,
render: render.New(render.Options{
Layout: "layout",
}),
}
return ctx
}
return engine
}
示例7: TestThrottleMaximum
func TestThrottleMaximum(t *testing.T) {
r := chi.NewRouter()
r.Use(ThrottleBacklog(50, 50, time.Second*5))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
time.Sleep(time.Second * 2) // Expensive operation.
w.Write(testContent)
})
server := httptest.NewServer(r)
client := http.Client{
Timeout: time.Second * 60, // Maximum waiting time.
}
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
res, err := client.Get(server.URL)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
buf, err := ioutil.ReadAll(res.Body)
assert.NoError(t, err)
assert.Equal(t, testContent, buf)
}(i)
}
// Wait less time than what the server takes to reply.
time.Sleep(time.Second * 1)
// At this point the server is still processing, all the following request
// will be beyond the server capacity.
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
res, err := client.Get(server.URL)
assert.NoError(t, err)
buf, err := ioutil.ReadAll(res.Body)
assert.Equal(t, http.StatusServiceUnavailable, res.StatusCode)
assert.Equal(t, errCapacityExceeded, strings.TrimSpace(string(buf)))
}(i)
}
wg.Wait()
server.Close()
}
示例8: New
//New create all routers under one Handler
func New() http.Handler {
r := chi.NewRouter()
r.Mount("/auth", auth.Routes())
r.Mount("/apps", apps.Routes())
return r
}
示例9: Routes
//Routes returns chi's Router for Auth APIs
func Routes() chi.Router {
r := chi.NewRouter()
r.Post("/register", m.BodyParser(registerRequestBuilder, 512), register)
r.Post("/login", m.BodyParser(loginRequestBuilder, 512), login)
r.Head("/logout", logout)
return r
}
示例10: articleRouter
func articleRouter() http.Handler {
r := chi.NewRouter()
r.Get("/", listArticles)
r.Route("/:articleID", func(r chi.Router) {
r.Get("/", getArticle)
// r.Put("/", updateArticle)
// r.Delete("/", deleteArticle)
})
return r
}
示例11: TestThrottleTriggerGatewayTimeout
func TestThrottleTriggerGatewayTimeout(t *testing.T) {
r := chi.NewRouter()
r.Use(ThrottleBacklog(50, 100, time.Second*5))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
time.Sleep(time.Second * 10) // Expensive operation.
w.Write(testContent)
})
server := httptest.NewServer(r)
client := http.Client{
Timeout: time.Second * 60, // Maximum waiting time.
}
var wg sync.WaitGroup
// These requests will be processed normally until they finish.
for i := 0; i < 50; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
res, err := client.Get(server.URL)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
}(i)
}
time.Sleep(time.Second * 1)
// These requests will wait for the first batch to complete but it will take
// too much time, so they will eventually receive a timeout error.
for i := 0; i < 50; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
res, err := client.Get(server.URL)
assert.NoError(t, err)
buf, err := ioutil.ReadAll(res.Body)
assert.Equal(t, http.StatusServiceUnavailable, res.StatusCode)
assert.Equal(t, errTimedOut, strings.TrimSpace(string(buf)))
}(i)
}
wg.Wait()
server.Close()
}
示例12: main
func main() {
r := chi.NewRouter()
// Limit to 5 requests globally.
r.Use(throttler.Limit(5))
r.Get("/*", handler)
admin := chi.NewRouter()
// Limit to 2 requests for admin route
admin.Use(throttler.Limit(2))
admin.Get("/", handler)
r.Mount("/admin/", admin)
fmt.Printf("Try running the following commands (in different terminal):\n\n")
fmt.Printf("for i in `seq 1 10`; do (curl 127.0.0.1:8000/ &); done\n\n")
fmt.Printf("for i in `seq 1 10`; do (curl 127.0.0.1:8000/admin/ &); done\n\n")
http.ListenAndServe(":8000", r)
}
示例13: initChi
func initChi() {
h := chi.NewRouter()
h.Get("/", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "Hello, World")
})
h.Get("/:name", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "Hello, %s", chi.URLParams(ctx)["name"])
})
registerHandler("chi", h)
}
示例14: Profiler
func Profiler() http.Handler {
r := chi.NewRouter()
r.Handle("/vars", expVars)
r.Handle("/pprof/", pprof.Index)
r.Handle("/pprof/cmdline", pprof.Cmdline)
r.Handle("/pprof/profile", pprof.Profile)
r.Handle("/pprof/symbol", pprof.Symbol)
r.Handle("/pprof/block", pprof.Handler("block").ServeHTTP)
r.Handle("/pprof/heap", pprof.Handler("heap").ServeHTTP)
r.Handle("/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP)
r.Handle("/pprof/threadcreate", pprof.Handler("threadcreate").ServeHTTP)
return r
}
示例15: main
func main() {
r := chi.NewRouter()
// use middleware
r.Use(middleware.Logger)
// add routing
r.Get("/", apiIndex)
r.Route("/todo", func(r chi.Router) {
r.Get("/", getTodoList)
})
http.ListenAndServe(":3333", r)
}