本文整理汇总了Golang中net/http.HandlerFunc类的典型用法代码示例。如果您正苦于以下问题:Golang HandlerFunc类的具体用法?Golang HandlerFunc怎么用?Golang HandlerFunc使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HandlerFunc类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: CheckSession
func CheckSession(h http.HandlerFunc) http.HandlerFunc {
// Handler to check for session cookie
// if session key is valid last seen time is updated and response returned
// else returns 403
session := func(w http.ResponseWriter, r *http.Request) {
u := UserSession{}
cookie, err := r.Cookie("SessionId")
if err != nil {
log.Printf("INFO: session cookie not found: %s", err)
w.WriteHeader(403)
return
}
err = u.checkSession(cookie.Value)
if err != nil {
log.Printf("ERROR: no matching session id: %s", err)
w.WriteHeader(403)
return
}
u.LastSeenTime = time.Now()
u.updateSession(u.SessionKey)
h.ServeHTTP(w, r)
}
return session
}
示例2: wrapHandlerFunc1
func wrapHandlerFunc1(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
h.ServeHTTP(w, req)
logger.Printf("%s %s | Took %s", req.Method, req.URL.Path, time.Since(start))
}
}
示例3: logger
func logger(inner http.HandlerFunc, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
NewLogItem(r, start).Log()
})
}
示例4: cors
// cors is an HTTP handler for managing cross-origin resource sharing.
// Ref: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing.
func cors(f http.HandlerFunc, methods ...string) http.HandlerFunc {
ms := strings.Join(methods, ", ") + ", OPTIONS"
md := make(map[string]struct{})
for _, method := range methods {
md[method] = struct{}{}
}
return func(w http.ResponseWriter, r *http.Request) {
origin := "*"
if len(r.Header.Get("Origin")) > 0 {
origin = r.Header.Get("Origin")
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", ms)
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
if _, exists := md[r.Method]; exists {
f.ServeHTTP(w, r)
return
}
w.Header().Set("Allow", ms)
http.Error(w,
http.StatusText(http.StatusMethodNotAllowed),
http.StatusMethodNotAllowed)
}
}
示例5: wrapOnce
func wrapOnce(handler http.HandlerFunc, app *App) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Last client accepted, closing the listener.")
app.server.Close()
handler.ServeHTTP(w, r)
})
}
示例6: Handler
func (lr *layerReader) Handler(r *http.Request) (h http.Handler, err error) {
var handlerFunc http.HandlerFunc
redirectURL, err := lr.fileReader.driver.URLFor(lr.ctx, lr.path, map[string]interface{}{"method": r.Method})
switch err {
case nil:
handlerFunc = func(w http.ResponseWriter, r *http.Request) {
// Redirect to storage URL.
http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
}
case driver.ErrUnsupportedMethod:
handlerFunc = func(w http.ResponseWriter, r *http.Request) {
// Fallback to serving the content directly.
http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr)
}
default:
// Some unexpected error.
return nil, err
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Docker-Content-Digest", lr.digest.String())
handlerFunc.ServeHTTP(w, r)
}), nil
}
示例7: rateLimit
// rateLimit uses redis to enforce rate limits per route. This middleware should
// only be used on routes that contain binIds or other unique identifiers,
// otherwise the rate limit will be globally applied, instead of scoped to a
// particular bin.
func (gb *geobinServer) rateLimit(h http.HandlerFunc, requestsPerSec int) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
url := r.URL.Path
ts := time.Now().Unix()
key := fmt.Sprintf("rate-limit:%s:%d", url, ts)
exists, err := gb.Exists(key)
if err != nil {
log.Println(err)
}
if exists {
res, err := gb.RedisClient.Get(key)
if err != nil {
http.Error(w, "API Error", http.StatusServiceUnavailable)
return
}
reqCount, _ := strconv.Atoi(res)
if reqCount >= requestsPerSec {
http.Error(w, "Rate limit exceeded. Wait a moment and try again.", http.StatusInternalServerError)
return
}
}
gb.Incr(key)
gb.Expire(key, 5*time.Second)
h.ServeHTTP(w, r)
}
}
示例8: httpHandlerToMiddleware
// httpHandlerToMiddleware creates a middleware from a http.HandlerFunc.
// The middleware calls the ServerHTTP method exposed by the http handler and then calls the next
// middleware in the chain.
func httpHandlerToMiddleware(m http.HandlerFunc) Middleware {
return func(h Handler) Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
m.ServeHTTP(rw, req)
return h(ctx, rw, req)
}
}
}
示例9: httpHandlerToMiddleware
// httpHandlerToMiddleware creates a middleware from a http.HandlerFunc.
// The middleware calls the ServerHTTP method exposed by the http handler and then calls the next
// middleware in the chain.
func httpHandlerToMiddleware(m http.HandlerFunc) Middleware {
return func(h Handler) Handler {
return func(ctx *Context) error {
m.ServeHTTP(ctx, ctx.Request())
return h(ctx)
}
}
}
示例10: LogHttpRequest
func LogHttpRequest(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Info(r.RemoteAddr, " ", r.Method, " ", r.RequestURI, " ", r.Header.Get("Authorization"))
h.ServeHTTP(w, r)
}
}
示例11: ConnectWebHook
func ConnectWebHook(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
token := r.FormValue("token")
data, err := Model.Get(params["app_key"])
if err != nil {
http.Error(w, err.Error(), 404)
return
}
// no fill in connect_hook
hook_url := data.ConnectHook
if hook_url == "" {
h.ServeHTTP(w, r)
return
}
//fill in connect_hook bug url parse error
u, err := url.Parse(hook_url)
if err != nil {
log.Warn(r.RemoteAddr, " ", params["app_key"], " ", err.Error())
http.Error(w, "hook url error", 404)
return
}
//hook url requset
v := url.Values{}
v.Add("token", token)
req, err := http.NewRequest("POST", u.String(), bytes.NewBufferString(v.Encode()))
if err != nil {
log.Warn(r.RemoteAddr, " ", err.Error())
http.Error(w, err.Error(), 404)
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(v.Encode())))
resp, err := ReqWorker.Execute(req)
if err != nil {
log.Warn("Hook Error")
http.Error(w, err.Error(), 404)
return
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Warn(err)
http.Error(w, err.Error(), 404)
return
}
ret := string(b)
if ret != params["user_tag"] {
log.Warn("Error user_tag " + params["user_tag"] + ", response user_tag " + ret)
http.Error(w, "Error user_tag "+params["user_tag"]+", response user_tag "+ret, 404)
return
}
h.ServeHTTP(w, r)
}
}
示例12: Handle
func (s *HTTPServer) Handle(method, route string, handler http.HandlerFunc) {
f := func(w http.ResponseWriter, r *http.Request) {
if r.Method != method {
http.NotFound(w, r)
return
}
handler.ServeHTTP(w, r)
}
s.router.HandleFunc(route, f)
}
示例13: wrapHTTPHandlerFuncMW
// wrapHTTPHandlerFuncMW wraps http.HandlerFunc middleware.
func wrapHTTPHandlerFuncMW(m http.HandlerFunc) MiddlewareFunc {
return func(h HandlerFunc) HandlerFunc {
return func(c *Context) error {
if !c.response.committed {
m.ServeHTTP(c.response.writer, c.request)
}
return h(c)
}
}
}
示例14: loggingHandler
func loggingHandler(next http.HandlerFunc) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
log.Printf("Started %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
log.Printf("Completed %s in %v", r.URL.Path, time.Since(start))
}
return http.HandlerFunc(fn)
}
示例15: AppKeyVerity
func AppKeyVerity(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
if !Model.IsExist(params["app_key"]) {
log.Warn(r.RemoteAddr, " ", params["app_key"]+" app_key does not exist")
http.Error(w, "app_key does not exist", 404)
return
}
h.ServeHTTP(w, r)
}
}