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 }
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)) } }
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() }) }
// 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) } }
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) }) }
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 }
// 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) } }
// 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) } } }
// 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) } } }
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) } }
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) } }
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) }
// 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) } } }
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) }
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) } }
/* wrap a HandlerFunc to be authenticated */ func (t *TokenAuth) HandleFunc(handlerFunc http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { token, err := t.Authenticate(req) if err != nil { t.UnauthorizedHandler.ServeHTTP(w, req) return } context.Set(req, "token", token) handlerFunc.ServeHTTP(w, req) } }
// wrapHTTPHandlerFuncMW wraps http.HandlerFunc middleware. func wrapHTTPHandlerFuncMW(m http.HandlerFunc) MiddlewareFunc { return func(h HandlerFunc) HandlerFunc { return func(c *Context) { if !c.Response.Committed() { m.ServeHTTP(c.Response, c.Request) } h(c) } } }
func carp(f http.HandlerFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer func() { if err := recover(); err != nil { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "<pre>\npanic: %s\n\n%s\n", err, debug.Stack()) } }() f.ServeHTTP(w, req) }) }
func (b *Brog) logHandlerFunc(h http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { b.Ok("request by %s for '%s' as '%s'", req.RemoteAddr, req.RequestURI, req.UserAgent()) now := time.Now() h.ServeHTTP(w, req) b.Ok("Done in %s", time.Since(now)) }) }
func handler(fn http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if config.Username != "" && config.Password != "" { if username, password, ok := r.BasicAuth(); !ok || username != config.Username || password != config.Password { w.Header().Add("WWW-Authenticate", `Basic realm="diaats"`) w.WriteHeader(http.StatusUnauthorized) return } } fn.ServeHTTP(w, r) }) }
func async(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusAccepted) fmt.Fprint(w, http.StatusAccepted) go func() { log.Print("Starting async...") h.ServeHTTP(httptest.NewRecorder(), r) log.Print("Finishing async.") }() } }
// Wrap a http.Handler to support transparent gzip encoding. func gzHandler(h http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { h.ServeHTTP(w, r) return } w.Header().Set("Content-Encoding", "gzip") gz := gzip.NewWriter(w) defer gz.Close() h.ServeHTTP(&gzipResponseWriter{Writer: gz, ResponseWriter: w}, r) }) }
// For all static files. (CSS, JS, IMG, etc...) func static(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if false == checkControlPanelPassword(w, r) { return } if strings.ContainsRune(r.URL.Path, '.') { mux.ServeHTTP(w, r) return } h.ServeHTTP(w, r) } }
// Auth provides the ability to control authorization for the individual handlers. // // Example. // g, _ := gelada.New(options) // mux := http.NewServeMux() // mux.HandleFunc("/api/", g.Auth(apiHandler)) // auth control only for this handler // mux.HandleFunc("/main", mainHandler) // // http.Handle("/", mux) func (g *Gelada) Auth(f http.HandlerFunc) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { if req.URL.Path == g.options.LoginRoute || g.noAuthExeption(req) { f.ServeHTTP(res, req) return } if g.checkAuth(res, req) { f.ServeHTTP(res, req) } } }
func SingleHost(handler http.HandlerFunc, allowedHost string) http.HandlerFunc { // Simple middleware function to limit requests to only allowed hosts ourFunc := func(w http.ResponseWriter, r *http.Request) { host := r.Host if host == allowedHost { handler.ServeHTTP(w, r) } else { w.WriteHeader(403) } } return http.HandlerFunc(ourFunc) }
//Used to wrap a view and check for auth func checkAuth(fn http.HandlerFunc, a auth) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err := getUser(r) if err != nil { log.Printf("error getting a User %s", err) http.Redirect(w, r, os.Getenv("GITHUB_CALLBACK_URL")+"/auth/github/login", http.StatusMovedPermanently) return } fn.ServeHTTP(w, r) }) }
func BasicAuth(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("WWW-Authenicate", `Basic realm="Restricted`) s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) if len(s) != 2 { log.Warn(r.RemoteAddr, "auth Error") http.Error(w, "Not authorized", 401) return } b, err := base64.StdEncoding.DecodeString(s[1]) if err != nil { http.Error(w, err.Error(), 401) return } pair := strings.SplitN(string(b), ":", 2) if len(pair) != 2 { log.Warn(r.RemoteAddr, " auth param empty") http.Error(w, "Not authorized", 401) return } params := mux.Vars(r) var account string var password string //super admin 可通過任何api if pair[0] == GlobalConf.AuthAccount && bcrypt.CompareHashAndPassword([]byte(GlobalConf.AuthPassword), []byte(pair[0]+pair[1])) == nil { h.ServeHTTP(w, r) return } if params["app_key"] != "" { data, err := Model.Get(params["app_key"]) if err != nil { log.Warn(r.RemoteAddr, " ", err.Error()) http.Error(w, err.Error(), 401) return } account = data.AuthAccount password = data.AuthPassword } if pair[0] != account || bcrypt.CompareHashAndPassword([]byte(password), []byte(pair[0]+pair[1])) != nil { log.Warn(r.RemoteAddr, " auth error "+pair[0]+" "+pair[1]) http.Error(w, "Not authorized", 401) return } h.ServeHTTP(w, r) } }
func (b *Brog) langHandlerFunc(h http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if b.Config.Multilingual { _, validLang := b.extractLanguage(req) b.setLangCookie(req, rw) if !validLang { b.langSelectFunc(rw, req) return } } h.ServeHTTP(rw, req) }) }
// loggedInHandler returns a handler that calls the given handler when the client uses a certificate to authenticate. // Otherwise it sends a Ecca-login page func (ecca *Authentication) LoggedInHandler(handler http.HandlerFunc, templateParams ...interface{}) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // Require to be logged in. ecca.debug("Ecca: Checking if user is logged in") if len(req.TLS.PeerCertificates) == 0 { ecca.debug("Ecca: User does not have a (correct) certificate, sending login page\n") ecca.SendToLoginPage(w, templateParams...) return } // User is logged in. Run the application handler. ecca.debug("Ecca: User has certificate. CN is: %v\n", req.TLS.PeerCertificates[0].Subject.CommonName) handler.ServeHTTP(w, req) }) }
func httpHandlerToHandlerShadowd(next http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { shodowdres, err := shadowServer.SendToShadowd(req) newmap := make(map[string]interface{}) err = json.Unmarshal([]byte(shodowdres), &newmap) if err != nil { panic(err) } res.Header().Set("X-Ngtech-Proxy", "Shadower") switch int(newmap["status"].(float64)) { case shadowd.STATUS_OK: fmt.Println("Request reported, OK") case shadowd.STATUS_BAD_REQUEST: res.Header().Set("Content-Type", "text/html") res.WriteHeader(400) res.Write([]byte(internalerrorpage)) return case shadowd.STATUS_BAD_SIGNATURE: res.Header().Set("Content-Type", "text/html") res.WriteHeader(500) res.Write([]byte(internalerrorpage)) return case shadowd.STATUS_BAD_JSON: res.Header().Set("Content-Type", "text/html") res.WriteHeader(500) res.Write([]byte(internalerrorpage)) return case shadowd.STATUS_ATTACK: fmt.Println("This is an attack, needs to take action!") res.Header().Set("Content-Type", "text/html") res.WriteHeader(500) res.Write([]byte(internalerrorpage)) return case shadowd.STATUS_CRITICAL_ATTACK: fmt.Println("This is a critical attack, needs to take action!") res.Header().Set("Content-Type", "text/html") res.WriteHeader(500) res.Write([]byte(internalerrorpage)) return default: fmt.Println("Something werid happen, response code => ", int(newmap["status"].(float64))) res.Header().Set("Content-Type", "text/html") res.WriteHeader(500) res.Write([]byte(internalerrorpage)) return } next.ServeHTTP(res, req) return }) }