当前位置: 首页>>代码示例>>Golang>>正文


Golang xhandler.HandlerFuncC函数代码示例

本文整理汇总了Golang中github.com/rs/xhandler.HandlerFuncC函数的典型用法代码示例。如果您正苦于以下问题:Golang HandlerFuncC函数的具体用法?Golang HandlerFuncC怎么用?Golang HandlerFuncC使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了HandlerFuncC函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ExampleAddChain

func ExampleAddChain() {
	c := xhandler.Chain{}

	close := xhandler.CloseHandler
	cors := cors.Default().Handler
	timeout := xhandler.TimeoutHandler(2 * time.Second)
	auth := func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			if v := ctx.Value("Authorization"); v == nil {
				http.Error(w, "Not authorized", http.StatusUnauthorized)
				return
			}
			next.ServeHTTPC(ctx, w, r)
		})
	}

	c.Add(close, cors, timeout)

	mux := http.NewServeMux()

	// Use c.Handler to terminate the chain with your final handler
	mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page!")
	})))

	// Create a new chain from an existing one, and add route-specific middleware to it
	protected := c.With(auth)

	mux.Handle("/admin", protected.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "protected endpoint!")
	})))
}
开发者ID:stellar,项目名称:bridge-server,代码行数:32,代码来源:chain_example_test.go

示例2: main

func main() {
	router := xmux.New()

	router.GET("/unoconv/health", xhandler.HandlerFuncC(healthHandler))
	router.POST("/unoconv/:filetype", xhandler.HandlerFuncC(unoconvHandler))
	log.Fatal(http.ListenAndServe(":3000", mw.Handler(router)))
}
开发者ID:HeavyHorst,项目名称:unoconv-api,代码行数:7,代码来源:main.go

示例3: router

func router(a *server) http.Handler {
	mux := xmux.New()

	c := xhandler.Chain{}

	c.Use(mwLogger)
	c.Use(mwAuthenticationCheck(a.key))

	mux.GET("/sites", c.HandlerCF(xhandler.HandlerFuncC(a.handleAllSites)))
	mux.GET("/sites/:id", c.HandlerCF(xhandler.HandlerFuncC(a.handleSingleSite)))
	mux.GET("/torrents", c.HandlerCF(xhandler.HandlerFuncC(a.handleTorrents)))
	mux.POST("/download/:hash", c.HandlerCF(xhandler.HandlerFuncC(a.handleDownload)))

	return xhandler.New(context.Background(), mux)
}
开发者ID:intfrr,项目名称:magopie,代码行数:15,代码来源:main.go

示例4: Callback

// Callback handles the oidc/oauth2 callback after a login attempt from the user.
// If the idenity provider returned a proof for valid login, the userid is stored in the session.
// This includes the model lookup and a possible creation for new users.
// The users last login timestamp is updated.
func (c *AuthController) Callback(successURL string) xhandler.HandlerC {
	return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		log.Info("Handler: Callback")
		user, err := c.Provider.Callback(w, r)

		if err != nil {
			log.Printf("Error occurred: %s", err)
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}
		if user == nil {
			log.Printf("Error occurred uid is nil")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}
		uuid := c.ProviderName + ":" + user["id"]

		u, err := c.loginUser(uuid, user["name"])
		if err != nil {
			log.Warnf("Could not create new user: %s", err)
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}
		session := ctx.Value("session").(*sessions.Session)
		session.Values["user"] = u.ID
		session.Save(r, w)

		http.Redirect(w, r, successURL, http.StatusFound)
	})
}
开发者ID:blang,项目名称:posty,代码行数:34,代码来源:auth.go

示例5: Login

// Login handles login requests and delegates to the oidc provider.
func (c *AuthController) Login() xhandler.HandlerC {
	return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		log.Info("Handler: Login")
		c.Provider.NewAuth(w, r)
		return
	})
}
开发者ID:blang,项目名称:posty,代码行数:8,代码来源:auth.go

示例6: TestNewHandlerWrongAudience

func TestNewHandlerWrongAudience(t *testing.T) {
	c := Config{
		Secret:    "5d63GMY5fRsBRdB7cDsMoLlNX9vWxNSq",
		Issuer:    "dmiss",
		Audiences: []string{"aud1", "aud2"},
	}
	h := NewHandler(c)
	xh := h(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))

	tok, err := generateToken()
	if err != nil {
		t.Fatalf("generateToken() - error encoding claim: %s", err)
	}
	fullPath := "/?access_token=" + tok

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", fullPath, nil)

	xh.ServeHTTPC(context.Background(), w, r)

	if want, got := http.StatusForbidden, w.Code; want != got {
		t.Errorf("TestNewHandlerWrongAudience http code: want %d got %d", want, got)
	}
}
开发者ID:dailymotion,项目名称:xjwt,代码行数:26,代码来源:xjwt_test.go

示例7: ToHandler

// ToHandler - Converts function to middleware.
func ToHandler(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request, next xhandler.HandlerC)) Handler {
	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			fn(ctx, w, r, next)
		})
	}
}
开发者ID:crackcomm,项目名称:renderer,代码行数:8,代码来源:handler.go

示例8: HandleFunc

// HandleFunc regiester a standard http.HandlerFunc request handler with the given
// path and method. With this adapter, your handler won't have access to the
// context and thus won't work with URL parameters.
func (mux *Mux) HandleFunc(method, path string, handler http.HandlerFunc) {
	mux.HandleC(method, path,
		xhandler.HandlerFuncC(func(_ context.Context, w http.ResponseWriter, r *http.Request) {
			handler(w, r)
		}),
	)
}
开发者ID:ory-am,项目名称:workshop-dbg,代码行数:10,代码来源:mux.go

示例9: TestMuxLookup

func TestMuxLookup(t *testing.T) {
	routed := false
	wantHandler := xhandler.HandlerFuncC(func(_ context.Context, _ http.ResponseWriter, _ *http.Request) {
		routed = true
	})

	mux := New()

	// try empty router first
	handler, _, tsr := mux.Lookup("GET", "/nope")
	assert.Nil(t, handler, "Got handle for unregistered pattern: %v", handler)
	assert.False(t, tsr, "Got wrong TSR recommendation!")

	// insert route and try again
	mux.GET("/user/:name", wantHandler)

	handler, params, tsr := mux.Lookup("GET", "/user/gopher")
	if assert.NotNil(t, handler) {
		handler.ServeHTTPC(nil, nil, nil)
		assert.True(t, routed, "Routing failed!")
	}

	assert.Equal(t, newParams("name", "gopher"), params)

	handler, _, tsr = mux.Lookup("GET", "/user/gopher/")
	assert.Nil(t, handler, "Got handle for unregistered pattern: %v", handler)
	assert.True(t, tsr, "Got no TSR recommendation!")

	handler, _, tsr = mux.Lookup("GET", "/nope")
	assert.Nil(t, handler, "Got handle for unregistered pattern: %v", handler)
	assert.False(t, tsr, "Got wrong TSR recommendation!")
}
开发者ID:patrickToca,项目名称:xmux,代码行数:32,代码来源:mux_test.go

示例10: middlewareByName

func middlewareByName(opts Options) (Handler, error) {
	descriptors := Descriptors()
	sort.Sort(byName(descriptors))

	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			name, err := opts.String(ctx, optMiddlewareName)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			reskey, _ := opts.String(ctx, optMiddlewareDestination)

			for _, desc := range descriptors {
				if desc.Name == name {
					ctx = components.WithTemplateKey(ctx, reskey, desc)
					break
				}
			}

			next.ServeHTTPC(ctx, w, r)
		})
	}, nil
}
开发者ID:crackcomm,项目名称:renderer,代码行数:25,代码来源:special.go

示例11: NewHandler

func NewHandler(c Config) func(xhandler.HandlerC) xhandler.HandlerC {
	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			var auth bool

			// Skip verification of path is in skip list.
			for _, skipPath := range c.Skip {
				if r.URL.Path == skipPath {
					auth = true
					break
				}
			}

			if !auth && c.Secret != "" {
				// Check token credentials.
				auth = checkToken(c, r)
			}

			// Check basic auth if no authorization based on token.
			if !auth && c.BasicUser != "" && c.BasicPass != "" {
				auth = checkBasicAuth(c, w, r)
			}

			if auth {
				next.ServeHTTPC(ctx, w, r)
			} else {
				http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			}
		})
	}
}
开发者ID:dailymotion,项目名称:xjwt,代码行数:31,代码来源:xjwt.go

示例12: ExampleNewHandler

func ExampleNewHandler() {
	c := xhandler.Chain{}

	// Install the metric handler with dogstatsd backend client and some env tags
	flushInterval := 5 * time.Second
	tags := []string{"role:my-service"}
	statsdWriter, err := net.Dial("udp", "127.0.0.1:8126")
	if err != nil {
		log.Fatal(err)
	}
	c.UseC(xstats.NewHandler(dogstatsd.New(statsdWriter, flushInterval), tags))

	// Here is your handler
	h := c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		// Get the xstats request's instance from the context. You can safely assume it will
		// be always there, if the handler is removed, xstats.FromContext will return a nop
		// instance.
		m := xstats.FromContext(ctx)

		// Count something
		m.Count("requests", 1, "route:index")
	}))

	http.Handle("/", h)

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}
开发者ID:patrickToca,项目名称:xstats,代码行数:29,代码来源:handler_example_test.go

示例13: TestMuxPanicHandler

func TestMuxPanicHandler(t *testing.T) {
	mux := New()
	panicHandled := false

	mux.PanicHandler = func(ctx context.Context, w http.ResponseWriter, r *http.Request, p interface{}) {
		panicHandled = true
	}

	mux.HandleC("PUT", "/user/:name", xhandler.HandlerFuncC(func(_ context.Context, _ http.ResponseWriter, _ *http.Request) {
		panic("oops!")
	}))

	w := new(mockResponseWriter)
	req, _ := http.NewRequest("PUT", "/user/gopher", nil)

	defer func() {
		if rcv := recover(); rcv != nil {
			t.Fatal("handling panic failed")
		}
	}()

	mux.ServeHTTPC(context.Background(), w, req)

	assert.True(t, panicHandled, "simulating failed")
}
开发者ID:patrickToca,项目名称:xmux,代码行数:25,代码来源:mux_test.go

示例14: MethodHandler

// MethodHandler returns a handler setting the request's method as a field
// to the current context's logger using the passed name as field name.
func MethodHandler(name string) func(next xhandler.HandlerC) xhandler.HandlerC {
	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			FromContext(ctx).SetField(name, r.Method)
			next.ServeHTTPC(ctx, w, r)
		})
	}
}
开发者ID:patrickToca,项目名称:xlog,代码行数:10,代码来源:handler.go

示例15: JSONWrapper

// JSONWrapper sets the content-type of the response to json.
func JSONWrapper() func(next xhandler.HandlerC) xhandler.HandlerC {
	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/vnd.api+json")
			next.ServeHTTPC(ctx, w, r)
		})
	}
}
开发者ID:blang,项目名称:posty,代码行数:9,代码来源:json.go


注:本文中的github.com/rs/xhandler.HandlerFuncC函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。