Exemplo n.º 1
0
func main() {
	middle := interpose.New()

	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`)
	})

	middle.UseHandler(router)

	// Now we will define a sub-router that uses the BasicAuth middleware
	// When you call any url starting with the path /protected, you will need to authenticate
	protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter()
	protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the protected page!")
	})

	// Define middleware that pertains to the part of the site protected behind HTTP Auth
	// and add the protected router to the protected middleware
	protectedMiddlew := interpose.New()
	protectedMiddlew.Use(middleware.BasicAuth("john", "doe"))
	protectedMiddlew.UseHandler(protectedRouter)

	// Add the protected middleware and its router to the main router
	router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew)

	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 2
0
func main() {
	middle := interpose.New()

	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`)
	})

	middle.UseHandler(router)

	// Now we will define a sub-router that uses the BasicAuth middleware
	// When you call any url starting with the path /protected, you will need to authenticate
	protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter()
	protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the protected page, %s!", context.Get(req, authKey))
	})

	protectedMiddlew := interpose.New()
	protectedMiddlew.Use(middleware.BasicAuthFunc(func(user, pass string, req *http.Request) bool {
		if middleware.SecureCompare(user, "admin") && middleware.SecureCompare(pass, "guessme") {
			context.Set(req, authKey, user)
			return true
		} else {
			return false
		}
	}))
	protectedMiddlew.Use(context.ClearHandler)
	protectedMiddlew.UseHandler(protectedRouter)

	router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew)

	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 3
0
func main() {
	middle := interpose.New()

	// Tell the browser which server this came from.
	// This modifies headers, so we want this to be called before
	// any middleware which might modify the body (in HTTP, the headers cannot be
	// modified after the body is modified)
	middle.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
			rw.Header().Set("X-Server-Name", "Interpose Test Server")
			next.ServeHTTP(rw, req)
		})
	})

	// Apply the router. By adding it last, all of our other middleware will be
	// executed before the router, allowing us to modify headers before any
	// output has been generated.
	router := mux.NewRouter()
	middle.UseHandler(router)

	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, middle)
}
func main() {
	middle := interpose.New()

	// Create a middleware that yields a global counter that increments until
	// the server is shut down. Note that this would actually require a mutex
	// or a channel to be safe for concurrent use. Therefore, this example is
	// unsafe.
	middle.Use(context.ClearHandler)
	middle.Use(func() func(http.Handler) http.Handler {
		c := 0

		return func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				c++
				context.Set(req, CountKey, c)
				next.ServeHTTP(w, req)
			})
		}
	}())

	// Apply the router.
	router := mux.NewRouter()
	router.HandleFunc("/test/{user}", func(w http.ResponseWriter, req *http.Request) {
		c, ok := context.GetOk(req, CountKey)
		if !ok {
			fmt.Println("Context not ok")
		}

		fmt.Fprintf(w, "Hi %s, this is visit #%d to the site since the server was last rebooted.", mux.Vars(req)["user"], c)

	})
	middle.UseHandler(router)

	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 5
0
func main() {
	mw := interpose.New()

	// Turn on output buffering. It's added first because it encapsulates all other output.
	// This enables headers to be written after data is sent, because they're all stored
	// in a buffer, so the user's browser will see everything in the order it expects.
	mw.Use(middleware.Buffer())

	// Tell the browser our output will be JSON. Note that because this is added
	// before the router, we will write JSON headers AFTER the router starts
	// writing output to the browser! Usually this would mean that the header would
	// not get set correctly. However, because we are buffering (see below),
	// nothing will get sent to the browser until all output is finished rendering.
	// This means that the header will get set correctly.
	mw.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Set("Content-Type", "application/json")
			next.ServeHTTP(w, req)
		})
	})

	// Apply the router.
	router := mux.NewRouter()
	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})
	mw.UseHandler(router)

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, mw)
}
Exemplo n.º 6
0
func main() {
	middle := interpose.New()

	// Send a header telling the world this is coming from an Interpose Test Server
	// You could imagine setting Content-type application/json or other useful
	// headers in other circumstances.
	middle.UseHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.Header().Set("X-Server-Name", "Interpose Test Server")
	}))

	// In this example, we use a basic router with a catchall route that
	// matches any path. In other examples in this project, we use a
	// more advanced router.
	// The last middleware added is the last executed, so by adding the router
	// last, our other middleware get a chance to modify HTTP headers before our
	// router writes to the HTTP Body
	router := http.NewServeMux()
	middle.UseHandler(router)

	router.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to %s!", req.URL.Path)
	}))

	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 7
0
func main() {
	mw := interpose.New()

	// Set a random integer everytime someone loads the page
	mw.Use(context.ClearHandler)
	mw.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			c := rand.Int()
			fmt.Println("Setting ctx count to:", c)
			context.Set(req, CountKey, c)
			next.ServeHTTP(w, req)
		})
	})

	// Apply the router.
	router := mux.NewRouter()
	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		c, ok := context.GetOk(req, CountKey)
		if !ok {
			fmt.Println("Get not ok")
		}

		fmt.Fprintf(w, "Welcome to the home page, %s!\nCount:%d", mux.Vars(req)["user"], c)

	})
	mw.UseHandler(router)

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, mw)
}
Exemplo n.º 8
0
func main() {
	mw := interpose.New()

	// Use unrolled's secure framework
	// If you inspect the headers, you will see X-Frame-Options set to DENY
	// Must be called before the router because it modifies HTTP headers
	secureMiddleware := secure.New(secure.Options{
		FrameDeny: true,
	})
	mw.Use(secureMiddleware.Handler)

	// Apply the router. By adding it first, all of our other middleware will be
	// executed before the router, allowing us to modify headers before any
	// output has been generated.
	router := mux.NewRouter()
	mw.UseHandler(router)

	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, mw)
}
Exemplo n.º 9
0
func Test_BasicAuthFunc(t *testing.T) {
	for auth, valid := range map[string]bool{
		"foo:spam":       true,
		"bar:spam":       true,
		"foo:eggs":       false,
		"bar:eggs":       false,
		"baz:spam":       false,
		"foo:spam:extra": false,
		"dummy:":         false,
		"dummy":          false,
		"":               false,
	} {
		recorder := httptest.NewRecorder()
		encoded := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))

		i := interpose.New()
		i.Use(BasicAuthFunc(func(username, password string, _ *http.Request) bool {
			return (username == "foo" || username == "bar") && password == "spam"
		}))

		i.Use(func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				w.Write([]byte("hello"))
				next.ServeHTTP(w, req)
			})
		})

		r, _ := http.NewRequest("GET", "foo", nil)

		i.ServeHTTP(recorder, r)

		if recorder.Code != 401 {
			t.Error("Response not 401, params:", auth)
		}

		if recorder.Body.String() == "hello" {
			t.Error("Auth block failed, params:", auth)
		}

		recorder = httptest.NewRecorder()
		r.Header.Set("Authorization", encoded)
		i.ServeHTTP(recorder, r)

		if valid && recorder.Code == 401 {
			t.Error("Response is 401, params:", auth)
		}
		if !valid && recorder.Code != 401 {
			t.Error("Response not 401, params:", auth)
		}

		if valid && recorder.Body.String() != "hello" {
			t.Error("Auth failed, got: ", recorder.Body.String(), "params:", auth)
		}
		if !valid && recorder.Body.String() == "hello" {
			t.Error("Auth block failed, params:", auth)
		}
	}
}
Exemplo n.º 10
0
func main() {
	middle := interpose.New()

	// Invoke the Gorilla framework's combined logger
	middle.Use(middleware.GorillaLog())

	// Create a router to serve HTTP content at two paths
	// and tell our middleware about the router
	router := mux.NewRouter()
	middle.UseHandler(router)

	router.PathPrefix("/green").Subrouter().Handle("/{name}", Green(http.HandlerFunc(welcomeHandler)))
	router.Handle("/{name}", http.HandlerFunc(welcomeHandler))

	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 11
0
func main() {
	middle := interpose.New()

	// First apply any middleware that will not write output to http body
	// but which may (or may not) modify headers
	middle.Use(middleware.GorillaLog())

	// Now apply any middleware that might modify the http body. This permits the
	// preceding middleware to alter headers
	router := mux.NewRouter()
	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})
	middle.UseHandler(router)

	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 12
0
func main() {
	router := mux.NewRouter()

	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	middle := interpose.New()

	// Use Martini-Auth, a Martini library for basic HTTP authentication
	middle.Use(adaptors.FromMartini(auth.Basic("user", "basic")))

	// Finally, add the router
	middle.UseHandler(router)

	// Now visit http://localhost:3001/guest and enter username "user"
	// and password "basic"
	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 13
0
func main() {
	middle := interpose.New()

	// First apply any middleware that will not write output to http body

	// Log to stdout. Taken from Gorilla
	middle.Use(middleware.GorillaLog())

	// Gzip output that follows. Taken from Negroni
	middle.Use(middleware.NegroniGzip(gzip.DefaultCompression))

	// Now apply any middleware that modify the http body.
	router := mux.NewRouter()
	middle.UseHandler(router)

	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	http.ListenAndServe(":3001", middle)
}
Exemplo n.º 14
0
func main() {
	router := mux.NewRouter()

	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	mw := interpose.New()

	// Use logrus
	x := negroni.Handler(negronilogrus.NewMiddleware())
	mw.Use(adaptors.FromNegroni(x))

	// Apply the router. By adding it last, all of our other middleware will be
	// executed before the router, allowing us to modify headers before any
	// output has been generated.
	mw.UseHandler(router)

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, mw)
}
Exemplo n.º 15
0
func main() {

	InitLogLevel()

	log.Println("Launching liveplant server")

	app, _ := NewApplication()
	middle := interpose.New()

	middle.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Set("Content-Type", "application/json")
			w.Header().Set("Access-Control-Allow-Origin", "*")
			next.ServeHTTP(w, req)
		})
	})

	middle.UseHandler(app.mux())

	ServerPort := "5000" // default port
	if len(os.Getenv("PORT")) > 0 {
		ServerPort = os.Getenv("PORT")
	}
	drainInterval, _ := time.ParseDuration("1s")
	srv := &graceful.Server{
		Timeout: drainInterval,
		Server: &http.Server{
			Addr:    ":" + ServerPort,
			Handler: middle,
		},
	}

	log.Println("Running liveplant server on port " + ServerPort)

	err := srv.ListenAndServe()
	if err != nil {
		log.Fatal(err.Error())
	}
}
Exemplo n.º 16
0
func main() {
	mw := interpose.New()

	// Tell the browser our output will be JSON
	mw.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Set("Content-Type", "application/json")
			next.ServeHTTP(w, req)
		})
	})

	// Apply the router. Because HTTP requires that headers be modified before
	// the body, the JSON header function must be added to the middleware stack
	// before the router.
	router := mux.NewRouter()
	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})
	mw.UseHandler(router)

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, mw)
}
Exemplo n.º 17
0
func main() {
	mw := interpose.New()

	// Invoke NoSurf (it modifies headers so must be called before your router)
	mw.Use(middleware.Nosurf())

	// Create and apply the router
	router := mux.NewRouter()
	mw.UseHandler(router)

	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		context := make(map[string]string)
		context["token"] = nosurf.Token(req)
		if req.Method == "POST" {
			context["name"] = req.FormValue("name")
		}

		templ.Execute(w, context)
	})

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, mw)
}
Exemplo n.º 18
0
func Test_BasicAuth(t *testing.T) {
	recorder := httptest.NewRecorder()
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("foo:bar"))

	i := interpose.New()
	i.Use(BasicAuth("foo", "bar"))
	i.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Write([]byte("hello"))
			next.ServeHTTP(w, req)
		})
	})

	r, _ := http.NewRequest("GET", "foo", nil)
	i.ServeHTTP(recorder, r)

	if recorder.Code != 401 {
		t.Errorf("recorder.Code wrong. Got %d wanted 401", recorder.Code)
	}

	if recorder.Body.String() == "hello" {
		t.Error("Auth block failed")
	}

	recorder = httptest.NewRecorder()
	r.Header.Set("Authorization", auth)
	i.ServeHTTP(recorder, r)

	if recorder.Code == 401 {
		t.Error("Response is 401")
	}

	if recorder.Body.String() != "hello" {
		t.Error("Auth failed, got: ", recorder.Body.String())
	}
}