コード例 #1
0
ファイル: main.go プロジェクト: andviro/noodle
func main() {
	// apiAuth guards access to api group
	apiAuth := mw.HTTPAuth("API", func(user, pass string) bool {
		return pass == "Secret"
	})
	// dashboardAuth guards access to dashboard group
	dashboardAuth := mw.HTTPAuth("Dashboard", func(user, pass string) bool {
		return pass == "Password"
	})

	// set up root router with Logger, Recovery and LocalStorage middleware
	w := wok.Default()

	// Index page
	idxTpl := template.Must(template.New("index").Parse("<h1>Hello</h1>"))
	w.GET("/", render.Template(idxTpl))(index)

	// api is a group of routes with common authentication and result rendering
	api := w.Group("/api", apiAuth, render.JSON)
	{
		api.GET("/")(apiIndex)
		api.GET("/:id")(apiDetail)
	}

	// dash is an example of another separate route group
	dash := w.Group("/dash", dashboardAuth)
	{
		tpl, _ := template.New("dash").Parse("<h1>Hello {{ .User }}</h1>")
		dash.GET("/", render.Template(tpl))(dashIndex)
	}

	http.ListenAndServe(":8080", w)
}
コード例 #2
0
ファイル: httpauth_test.go プロジェクト: andviro/noodle
func TestHttpAuth(t *testing.T) {
	is := is.New(t)
	n := noodle.New(mw.HTTPAuth("test", func(u, p string) bool {
		return p == "testPassword"
	})).Then(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		user := mw.GetUser(ctx)
		is.Equal(user, "testUser")
		return nil
	})

	r, _ := http.NewRequest("GET", "http://localhost", nil)
	w := httptest.NewRecorder()
	err := n(context.TODO(), w, r)
	is.Err(err)
	is.Equal(err, mw.UnauthorizedRequest)
	is.Equal(w.Code, http.StatusUnauthorized)
	is.Equal(w.Header().Get("WWW-Authenticate"), "Basic realm=test")

	r.SetBasicAuth("testUser", "wrongPassword")
	is.Err(n(context.TODO(), w, r))

	r.SetBasicAuth("testUser", "testPassword")
	is.NotErr(n(context.TODO(), w, r))
}