本文整理匯總了Golang中github.com/gorilla/context.ClearHandler函數的典型用法代碼示例。如果您正苦於以下問題:Golang ClearHandler函數的具體用法?Golang ClearHandler怎麽用?Golang ClearHandler使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ClearHandler函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Run
func (a *Api) Run() error {
globalMux := http.NewServeMux()
authRouter := mux.NewRouter()
authRouter.HandleFunc("/auth/login", a.login).Methods("GET")
authRouter.HandleFunc("/auth/logout", a.logout).Methods("GET")
authRouter.HandleFunc("/auth/callback", a.authCallback).Methods("GET")
apiRouter := mux.NewRouter()
apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.domains))).Methods("GET")
apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.addDomain))).Methods("POST")
apiRouter.Handle("/api/domains/{prefix:.*}", a.authRequiredMiddleware(http.HandlerFunc(a.removeDomain))).Methods("DELETE")
apiRouter.HandleFunc("/api/ip", a.getIP).Methods("GET")
//globalMux.Handle("/api/", apiRouter)
globalMux.Handle("/api/", apiRouter)
globalMux.Handle("/auth/", authRouter)
// global handler
globalMux.Handle("/", http.FileServer(http.Dir("static")))
s := &http.Server{
Addr: a.listenAddr,
Handler: context.ClearHandler(globalMux),
}
if err := s.ListenAndServe(); err != nil {
return err
}
return http.ListenAndServe(a.listenAddr, context.ClearHandler(globalMux))
}
示例2: main
func main() {
flag.Parse()
s, err := susigo.NewSusi(*susiaddr, *cert, *key)
if err != nil {
log.Printf("Error while creating susi connection: %v", err)
return
}
susi = s
log.Println("successfully create susi connection")
sessionTimeouts = make(map[string]time.Time)
if *user == "" && *pass == "" {
http.HandleFunc("/publish", publishHandler)
http.HandleFunc("/upload", uploadHandler)
http.Handle("/ws", websocket.Handler(websocketHandler))
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))))
http.HandleFunc("/", redirectToIndex)
} else {
http.HandleFunc("/publish", BasicAuth(publishHandler))
http.HandleFunc("/upload", BasicAuth(uploadHandler))
http.HandleFunc("/ws", BasicAuth(websocket.Handler(websocketHandler).ServeHTTP))
http.HandleFunc("/assets/", BasicAuth(http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))).ServeHTTP))
http.HandleFunc("/", BasicAuth(redirectToIndex))
}
log.Printf("starting http server on %v...", *webaddr)
if *useHTTPS {
log.Fatal(http.ListenAndServeTLS(*webaddr, *cert, *key, context.ClearHandler(http.DefaultServeMux)))
} else {
log.Fatal(http.ListenAndServe(*webaddr, context.ClearHandler(http.DefaultServeMux)))
}
}
示例3: main
func main() {
//Setup the logger
logger.InitLogger(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
//Read configuration information from server_config.json
config.ReadServerConf()
//The port our server listens on
listenPort := config.ServerConf.Port
logger.Info.Printf("Sever Starting - Listing on port %d - (Version - %s)", listenPort, consts.SERVER_VERSION)
//Create router
router := mux.NewRouter()
//Setup our routes
router.Handle("/people",
handlers.Execute(&handlers.PeopleHandler{},
handlers.AuthHandlerAdapter(),
handlers.DBConnAdapter())).Methods("GET")
router.Handle("/places",
handlers.Execute(&handlers.PlacesHandler{},
handlers.AuthHandlerAdapter(),
handlers.DBConnAdapter())).Methods("GET")
//Listen for connections and serve content
logger.Info.Println(http.ListenAndServe(":"+strconv.Itoa(listenPort),
context.ClearHandler(logger.HttpLog(router))))
}
示例4: Load
// Load the web server
func Load(c interfaces.Configuration) {
log.Debugln("Loading HTTP server")
config = c
auth.InitStore(config)
misc.Init(config)
util.Init(config)
http.HandleFunc("/history/", misc.History)
http.HandleFunc("/script/", misc.Script)
http.HandleFunc("/network/", misc.Network)
http.HandleFunc("/settings/", misc.Settings)
http.HandleFunc("/auth/login", auth.Login)
http.HandleFunc("/auth/confirm", auth.EmailConfirm)
http.HandleFunc("/auth/password/reset", auth.PasswordReset)
http.HandleFunc("/auth/password/forgot", auth.PasswordForgot)
http.HandleFunc("/auth/password/change", auth.PasswordChange)
http.HandleFunc("/auth/register", auth.Register)
http.HandleFunc("/auth/check", auth.HTTPCheck)
http.HandleFunc("/socket", socket.Serve)
err := http.ListenAndServe(config.GetAddr(), context.ClearHandler(http.DefaultServeMux))
if err != nil {
log.Fatalf("Failed to listen to %s: %s", config.GetAddr(), err)
log.Parent.Close()
os.Exit(4)
}
}
示例5: main
func main() {
globalMux := http.NewServeMux()
dockerUrl := "tcp://127.0.0.1:5554"
tlsCaCert := ""
tlsCert := ""
tlsKey := ""
allowInsecure := true
log.SetLevel(log.DebugLevel)
client, err := utils.GetClient(dockerUrl, tlsCaCert, tlsCert, tlsKey, allowInsecure)
if err != nil {
log.Fatal(err)
}
a := &Api{client, true, true, &sync.Mutex{}}
globalMux.Handle("/", http.FileServer(http.Dir("static")))
globalMux.Handle("/exec", websocket.Handler(a.execContainer))
globalMux.Handle("/ws", websocket.Handler(a.execContainer))
s := &http.Server{
Addr: "0.0.0.0:8081",
Handler: context.ClearHandler(globalMux),
}
var runErr error
runErr = s.ListenAndServe()
if runErr != nil {
log.Fatal(runErr)
}
}
示例6: main
func main() {
//Setup router
router := mux.NewRouter()
handlers.ConfigUserHandler(router.PathPrefix("/user").Subrouter())
handlers.ConfigFormHandler(router.PathPrefix("/form").Subrouter())
handlers.ConfigMiscHandlers(router.PathPrefix("/misc").Subrouter())
handlers.ConfigReviewHandler(router.PathPrefix("/review").Subrouter())
handlers.ConfigRecommHandler(router.PathPrefix("/recomm").Subrouter())
handlers.ConfigAdminHandler(router.PathPrefix("/gm").Subrouter())
http.Handle("/", router)
//Setup CORS Options
origins := make([]string, 1)
origins[0] = "*"
allowOrigins := goHandlers.AllowedOrigins(origins)
addrStr := fmt.Sprintf("%s:%d",
public.Config.GetString("server.address"),
public.Config.GetInt("server.port"))
public.LogV.Printf("Listen address: %s\n", addrStr)
public.LogE.Fatal(http.ListenAndServe(
addrStr,
context.ClearHandler(goHandlers.CORS(allowOrigins)(http.DefaultServeMux)),
))
}
示例7: startApp
func startApp(port string) {
// Load environment variables
envVars := loadEnvVars()
// Override with cloud foundry user provided service credentials if specified.
loadUPSVars(&envVars)
app, settings, err := controllers.InitApp(envVars)
if err != nil {
// Print the error.
fmt.Println(err.Error())
// Terminate the program with a non-zero value number.
// Need this for testing purposes.
os.Exit(1)
}
if settings.PProfEnabled {
pprof.InitPProfRouter(app)
}
if envVars.NewRelicLicense != "" {
fmt.Println("starting monitoring...")
startMonitoring(envVars.NewRelicLicense)
}
fmt.Println("starting app now...")
// TODO add better timeout message. By default it will just say "Timeout"
protect := csrf.Protect([]byte(envVars.SessionKey), csrf.Secure(settings.SecureCookies))
http.ListenAndServe(":"+port, protect(
http.TimeoutHandler(context.ClearHandler(app), helpers.TimeoutConstant, ""),
))
}
示例8: main
func main() {
fmt.Println("")
fmt.Println("")
fmt.Println("-------------------------STARTUP OF SERVER-------------------------")
if len(os.Args) < 2 {
panic("Cannot startup, the first argument must be the config path")
}
settings := NewDefaultSettings(os.Args[1])
ctx := RouterContext.New(settings)
router := mux.NewRouter()
setRouteDefinitions(ctx, router)
n := negroni.New(getNegroniHandlers(ctx, router)...) //negroni.Classic()
n.UseHandler(context.ClearHandler(router))
ctx.Logger.Info("Now serving on %s", settings.ServerBackendUrl())
backendUrl, err := url.Parse(settings.ServerBackendUrl())
CheckError(err)
hostWithPossiblePortOnly := backendUrl.Host
if settings.IsDevMode() {
graceful.Run(hostWithPossiblePortOnly, 0, n)
} else {
graceful.Run(hostWithPossiblePortOnly, 5*time.Second, n) //Graceful shutdown to allow 5 seconds to close connections
}
}
示例9: constructHTTPHandler
func (cmd *ATCCommand) constructHTTPHandler(
webHandler http.Handler,
apiHandler http.Handler,
oauthHandler http.Handler,
) http.Handler {
webMux := http.NewServeMux()
webMux.Handle("/api/v1/", apiHandler)
webMux.Handle("/auth/", oauthHandler)
webMux.Handle("/", webHandler)
var httpHandler http.Handler
httpHandler = webMux
// proxy Authorization header to/from auth cookie,
// to support auth from JS (EventSource) and custom JWT auth
httpHandler = auth.CookieSetHandler{
Handler: httpHandler,
}
// don't leak gorilla context per-request
httpHandler = context.ClearHandler(httpHandler)
return httpHandler
}
示例10: main
func main() {
var (
confPath string
)
flag.StringVar(&confPath, "f", "./ipcapcom.conf", "path to config file")
flag.Parse()
err := gcfg.ReadFileInto(&cfg, confPath)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading config file: %v\n", err)
os.Exit(1)
}
r := mux.NewRouter()
r.HandleFunc("/ping", handlePing).Methods("GET")
r.HandleFunc("/apply", handleApply).Methods("POST")
r.HandleFunc("/purge", handlePurge).Methods("GET")
r.PathPrefix("/").Handler(http.FileServer(http.Dir(cfg.General.StaticDir)))
http.Handle("/", context.ClearHandler(r))
go reaper()
err = http.ListenAndServe(":"+cfg.General.ListenPort, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
示例11: main
func main() {
flag.Parse()
var cfg Config
_, err := toml.DecodeFile(*configFilePath, &cfg)
if err != nil {
log.Fatal("Failed reading config file:", err)
}
if cfg.Log.Path != "" {
lf, err := os.Create(cfg.Log.Path)
if err != nil {
log.Fatal("Failed opening log file:", err)
}
log.SetOutput(lf)
}
if cfg.Server.BaseURL == "" {
log.Fatal("Missing required base-url setting")
}
// CSRF defeat: JSON-only API (reject non-JSON content types)
s := http.Server{
Addr: cfg.Server.Bind,
Handler: newJsonVerifier(context.ClearHandler(NewProxy(&cfg))),
}
log.Println("Proxy server listening on", cfg.Server.Bind)
err = s.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
示例12: setupRoutes
func (s *setupStruct) setupRoutes() {
commonMids := commonMiddlewares()
authMids := authMiddlewares()
normal := func(h http.HandlerFunc) httprouter.Handle {
return xhttp.Adapt(commonMids(h))
}
auth := func(h http.HandlerFunc) httprouter.Handle {
return xhttp.Adapt(commonMids(authMids(h)))
}
router := httprouter.New()
itemStore := stores.NewItemStore(s.Rethink)
userStore := stores.NewUserStore(s.Rethink)
{
itemCtrl := handlers.NewItemCtrl(itemStore)
router.GET("/v1/item", normal(itemCtrl.List))
router.GET("/v1/item/:id", normal(itemCtrl.Get))
router.POST("/v1/item", auth(itemCtrl.Create))
}
{
userCtrl := handlers.NewUserCtrl(userStore)
router.GET("/v1/user", normal(userCtrl.List))
router.GET("/v1/user/:id", normal(userCtrl.Get))
router.POST("/v1/user", auth(userCtrl.Create))
}
s.Handler = context.ClearHandler(router)
}
示例13: NewRouter
func NewRouter(appContext *ApplicationContext) *mux.Router {
opts := &respond.Options{
Before: func(w http.ResponseWriter, r *http.Request, status int, data interface{}) (int, interface{}) {
dataEnvelope := map[string]interface{}{"code": status}
if err, ok := data.(error); ok {
dataEnvelope["error"] = err.Error()
dataEnvelope["success"] = false
} else {
dataEnvelope["data"] = data
dataEnvelope["success"] = true
}
return status, dataEnvelope
},
}
router := mux.NewRouter()
for _, route := range routes {
var handler http.Handler
handler = opts.Handler(route.Handler)
handler = CORSHandler(ContextAwareHandler(handler, appContext), route)
handler = context.ClearHandler(handler)
router.
Methods([]string{route.Method, "OPTIONS"}...).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}
示例14: TestNewSession
func TestNewSession(t *testing.T) {
store := sessions.NewCookieStore([]byte("secret"))
fn := func(c web.C, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}
mux := web.New()
mux.Handle("/*", fn)
mux.Use(Middleware("session", store))
ts := httptest.NewServer(context.ClearHandler(mux))
defer ts.Close()
var err error
var resp *http.Response
resp, err = http.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
cookie := resp.Header.Get("Set-Cookie")
t.Logf("Set-Cookie: %v", cookie)
if cookie == "" {
t.Fatal("\"Set-Cookie\" header missing")
}
matches := sessionPattern.FindStringSubmatch(cookie)
if len(matches) != 2 {
t.Fatal("session cookie missing")
}
}
示例15: registerRoutes
func registerRoutes() http.Handler {
h := http.NewServeMux()
mux := pat.New()
// register routes
mux.Get("/", http.HandlerFunc(root))
mux.Get("/upload", oauthWrapper(http.HandlerFunc(uploadPage)))
mux.Post("/upload", oauthWrapper(http.HandlerFunc(uploadHandler)))
mux.Get("/auth", http.HandlerFunc(oauthRedirectHandler))
mux.Get("/search", http.HandlerFunc(searchPage))
mux.Get("/image/:hash", http.HandlerFunc(imagePage))
mux.Get("/:hash", http.HandlerFunc(getImageHandler))
mux.Get("/:hash/:width", http.HandlerFunc(getImageHandlerWidth))
mux.Get("/", http.HandlerFunc(root))
h.Handle("/", loggerMiddlerware(mux))
h.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
// load templates
templates = loadTemplates()
return context.ClearHandler(h)
}