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


Golang HandlerFunc.ServeHTTP方法代码示例

本文整理汇总了Golang中net/http.HandlerFunc.ServeHTTP方法的典型用法代码示例。如果您正苦于以下问题:Golang HandlerFunc.ServeHTTP方法的具体用法?Golang HandlerFunc.ServeHTTP怎么用?Golang HandlerFunc.ServeHTTP使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.HandlerFunc的用法示例。


在下文中一共展示了HandlerFunc.ServeHTTP方法的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
}
开发者ID:MajorMJR,项目名称:homesite,代码行数:27,代码来源:routes.go

示例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))
	}
}
开发者ID:agupt,项目名称:learn,代码行数:7,代码来源:wrap_other.go

示例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()
	})
}
开发者ID:maxtors,项目名称:go-suricatasc-api,代码行数:7,代码来源:handler.go

示例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)
	}
}
开发者ID:rinor,项目名称:sms-api-server,代码行数:30,代码来源:cors.go

示例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)
	})
}
开发者ID:kryptBlue,项目名称:gotty,代码行数:7,代码来源:app.go

示例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
}
开发者ID:orivej,项目名称:distribution,代码行数:26,代码来源:layerreader.go

示例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)
	}
}
开发者ID:kpettijohn,项目名称:geobin.io,代码行数:35,代码来源:geobinserver.go

示例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)
		}
	}
}
开发者ID:ajoulie,项目名称:goa,代码行数:11,代码来源:middleware.go

示例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)
		}
	}
}
开发者ID:minloved,项目名称:goa,代码行数:11,代码来源:middleware.go

示例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)

	}
}
开发者ID:syhlion,项目名称:gusher,代码行数:8,代码来源:middleware.go

示例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)
	}
}
开发者ID:syhlion,项目名称:gusher,代码行数:58,代码来源:middleware.go

示例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)
}
开发者ID:CadeLaRen,项目名称:nvidia-docker,代码行数:10,代码来源:graceful.go

示例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)
		}
	}
}
开发者ID:otsimo,项目名称:distribution,代码行数:11,代码来源:echo.go

示例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)
}
开发者ID:mukulrawat1986,项目名称:play,代码行数:10,代码来源:main.go

示例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)
	}
}
开发者ID:syhlion,项目名称:gusher,代码行数:11,代码来源:middleware.go


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