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


Golang http.HandlerFunc類代碼示例

本文整理匯總了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
}
開發者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類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。