當前位置: 首頁>>代碼示例>>Golang>>正文


Golang chi.NewRouter函數代碼示例

本文整理匯總了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()
}
開發者ID:chubais,項目名稱:chi,代碼行數:32,代碼來源:throttler_test.go

示例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)
}
開發者ID:pressly,項目名稱:chi,代碼行數:25,代碼來源:main.go

示例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)
	}
}
開發者ID:lacion,項目名稱:jwtauth,代碼行數:32,代碼來源:jwtauth_test.go

示例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
}
開發者ID:vladdy,項目名稱:chi,代碼行數:27,代碼來源:main.go

示例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
}
開發者ID:goware,項目名稱:jwtauth,代碼行數:31,代碼來源:main.go

示例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
}
開發者ID:ustrajunior,項目名稱:minion,代碼行數:26,代碼來源:minion.go

示例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()
}
開發者ID:chubais,項目名稱:chi,代碼行數:59,代碼來源:throttler_test.go

示例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
}
開發者ID:releasifier,項目名稱:releasifier,代碼行數:9,代碼來源:web.go

示例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
}
開發者ID:releasifier,項目名稱:releasifier,代碼行數:10,代碼來源:routes.go

示例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
}
開發者ID:pressly,項目名稱:chi,代碼行數:10,代碼來源:main.go

示例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()
}
開發者ID:chubais,項目名稱:chi,代碼行數:55,代碼來源:throttler_test.go

示例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)
}
開發者ID:DisruptiveMind,項目名稱:throttler,代碼行數:20,代碼來源:main.go

示例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)
}
開發者ID:najeira,項目名稱:go-frameworks-benchmark,代碼行數:12,代碼來源:chi.go

示例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
}
開發者ID:palaiyacw,項目名稱:imgry,代碼行數:13,代碼來源:middleware.go

示例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)
}
開發者ID:yudppp,項目名稱:chi-sample,代碼行數:14,代碼來源:main.go


注:本文中的github.com/pressly/chi.NewRouter函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。