本文整理匯總了Golang中github.com/codegangsta/martini.Classic函數的典型用法代碼示例。如果您正苦於以下問題:Golang Classic函數的具體用法?Golang Classic怎麽用?Golang Classic使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Classic函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Test_LoginRedirectAfterLoginRequired
func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
recorder := httptest.NewRecorder()
m := martini.Classic()
m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
m.Use(Google(&Options{
ClientId: "client_id",
ClientSecret: "client_secret",
RedirectURL: "refresh_url",
Scopes: []string{"x", "y"},
}))
m.Get("/login-required", LoginRequired, func(tokens Tokens) (int, string) {
return 200, tokens.Access()
})
r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
m.ServeHTTP(recorder, r)
location := recorder.HeaderMap["Location"][0]
if recorder.Code != 302 {
t.Errorf("Not being redirected to the auth page.")
}
if location != "/login?next=%2Flogin-required%3Fkey%3Dvalue" {
t.Errorf("Not being redirected to the right page, %v found", location)
}
}
示例2: Test_Validate
func Test_Validate(t *testing.T) {
m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(sessions.Sessions("my_session", store))
m.Use(Generate(&Options{
Secret: "token123",
SessionKey: "userID",
}))
// Simulate login.
m.Get("/login", func(s sessions.Session) string {
s.Set("userID", "123456")
return "OK"
})
// Generate token.
m.Get("/private", func(s sessions.Session, x CSRF) string {
return x.GetToken()
})
m.Post("/private", Validate, func(s sessions.Session) string {
return "OK"
})
// Login to set session.
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/login", nil)
m.ServeHTTP(res, req)
cookie := res.Header().Get("Set-Cookie")
// Get a new token.
res2 := httptest.NewRecorder()
req2, _ := http.NewRequest("GET", "/private", nil)
req2.Header.Set("Cookie", cookie)
m.ServeHTTP(res2, req2)
// Post using _csrf form value.
data := url.Values{}
data.Set("_csrf", res2.Body.String())
res3 := httptest.NewRecorder()
req3, _ := http.NewRequest("POST", "/private", bytes.NewBufferString(data.Encode()))
req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req3.Header.Set("Content-Length", strconv.Itoa(len(data.Encode())))
req3.Header.Set("Cookie", cookie)
m.ServeHTTP(res3, req3)
if res3.Code == 400 {
t.Error("Validation of _csrf form value failed")
}
// Post using X-CSRFToken HTTP header.
res4 := httptest.NewRecorder()
req4, _ := http.NewRequest("POST", "/private", nil)
req4.Header.Set("X-CSRFToken", res2.Body.String())
req4.Header.Set("Cookie", cookie)
m.ServeHTTP(res4, req4)
if res4.Code == 400 {
t.Error("Validation of X-CSRFToken failed")
}
}
示例3: Test_BasicAuth
func Test_BasicAuth(t *testing.T) {
res := httptest.NewRecorder()
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("gopher:golf"))
m := martini.Classic()
m.Get("/protected", AuthBasic(), func(w http.ResponseWriter, req *http.Request, b *Basic) {
fmt.Fprintf(w, "hi %s %s", b.Username, b.Password)
})
r, _ := http.NewRequest("GET", "/protected", nil)
m.ServeHTTP(res, r)
if res.Code != 401 {
t.Error("Response not 401")
}
if strings.Contains(res.Body.String(), "hi") {
t.Error("Auth block failed")
}
res = httptest.NewRecorder()
r.Header.Set("Authorization", auth)
m.ServeHTTP(res, r)
if res.Code == 401 {
t.Error("Response is 401")
}
if res.Body.String() != "hi gopher golf" {
t.Error("Auth failed, got: ", res.Body.String())
}
}
示例4: TestBind
func TestBind(t *testing.T) {
index := 0
for test, expectStatus := range bindTests {
recorder := httptest.NewRecorder()
handler := func(post BlogPost, errors Errors) { handle(test, t, index, post, errors) }
m := martini.Classic()
switch test.method {
case "GET":
m.Get(route, Bind(BlogPost{}), handler)
case "POST":
m.Post(route, Bind(BlogPost{}), handler)
}
req, err := http.NewRequest(test.method, test.path, strings.NewReader(test.payload))
req.Header.Add("Content-Type", test.contentType)
if err != nil {
t.Error(err)
}
m.ServeHTTP(recorder, req)
if recorder.Code != expectStatus {
t.Errorf("On test case %v, got status code %d but expected %d", test, recorder.Code, expectStatus)
}
index++
}
}
示例5: main
func main() {
m := martini.Classic()
m.Get("/", func() string {
return "Hello World"
})
m.Run()
}
示例6: testForm
func testForm(t *testing.T, withInterface bool) {
for index, test := range formTests {
recorder := httptest.NewRecorder()
handler := func(post BlogPost, errors Errors) { handle(test, t, index, post, errors) }
binding := Form(BlogPost{})
if withInterface {
handler = func(post BlogPost, errors Errors) {
post.Create(test, t, index)
}
binding = Form(BlogPost{}, (*Modeler)(nil))
}
m := martini.Classic()
switch test.method {
case "GET":
m.Get(route, binding, handler)
case "POST":
m.Post(route, binding, handler)
}
req, err := http.NewRequest(test.method, test.path, nil)
if err != nil {
t.Error(err)
}
m.ServeHTTP(recorder, req)
}
}
示例7: main
func main() {
// fmt.Println("Hello World!")
rand.Seed(time.Now().UTC().UnixNano())
/* database := models.GetDB()
database.Drop(tiedotmartini2.BAND_COL)
database.Drop(tiedotmartini2.LOCATION_COL)
database.Drop(tiedotmartini2.GENRE_COL)
database.Create(tiedotmartini2.BAND_COL, 1)
database.Create(tiedotmartini2.LOCATION_COL, 1)
database.Create(tiedotmartini2.GENRE_COL, 1)
col := database.Use(tiedotmartini2.BAND_COL)
col.Index([]string{"albums", "genre_id"})
database.Close()
*/
m := martini.Classic()
m.Get("/", controllers.HomeIndex)
m.Get("/home/index", controllers.HomeIndex)
m.Get("/band/add", controllers.BandAdd)
m.Post("/band/verify", controllers.BandVerify)
m.Get("/album/index/:id", controllers.AlbumIndex)
m.Get("/album/add/:id", controllers.AlbumAdd)
m.Post("/album/verify/:id", controllers.AlbumVerify)
m.Get("/home/genrelist", controllers.HomeGenreList)
m.Get("/home/bygenre/:id", controllers.HomeByGenre)
m.Use(martini.Static("assets"))
m.Run()
}
示例8: init
func init() {
m := martini.Classic()
m.Group("/api/stories", func(r martini.Router) {
r.Get("/", GetStories)
r.Get("/:key", GetStories)
r.Post("/new", NewStory)
r.Put("/update/:id", UpdateStory)
r.Delete("/delete/:id", DeleteStory)
})
m.Group("/api/tasks", func(r martini.Router) {
r.Get("/", GetTasks)
r.Get("/:key", GetTasks)
r.Post("/new", NewTask)
r.Put("/update/:key", UpdateTask)
r.Delete("/delete/:key", DeleteTask)
})
// add test-datas
m.Group("/testdatas", func(r martini.Router) {
r.Get("/story", AddTestDatasForStory)
//r.Get("/task", xxx)
})
http.Handle("/", m)
}
示例9: testEmptyJson
func testEmptyJson(t *testing.T) {
for index, test := range emptyPayloadTests {
recorder := httptest.NewRecorder()
handler := func(section BlogSection, errors Errors) { handleEmpty(test, t, index, section, errors) }
binding := Json(BlogSection{})
m := martini.Classic()
switch test.method {
case "GET":
m.Get(route, binding, handler)
case "POST":
m.Post(route, binding, handler)
case "PUT":
m.Put(route, binding, handler)
case "DELETE":
m.Delete(route, binding, handler)
}
req, err := http.NewRequest(test.method, route, strings.NewReader(test.payload))
if err != nil {
t.Error(err)
}
m.ServeHTTP(recorder, req)
}
}
示例10: Test_Render_NoRace
func Test_Render_NoRace(t *testing.T) {
// This test used to fail if run with -race
m := martini.Classic()
m.Use(Renderer(Options{
Directory: "fixtures/basic",
}))
// routing
m.Get("/foobar", func(r Render) {
r.HTML(200, "hello", "world")
})
done := make(chan bool)
doreq := func() {
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foobar", nil)
m.ServeHTTP(res, req)
expect(t, res.Code, 200)
expect(t, res.Header().Get(ContentType), ContentHTML+"; charset=UTF-8")
// ContentLength should be deferred to the ResponseWriter and not Render
expect(t, res.Header().Get(ContentLength), "")
expect(t, res.Body.String(), "<h1>Hello world</h1>\n")
done <- true
}
// Run two requests to check there is no race condition
go doreq()
go doreq()
<-done
<-done
}
示例11: main
func main() {
autoUpdate()
m := martini.Classic()
m.Use(martini.Static("static"))
m.Use(render.Renderer())
m.Get("/", func(r render.Render) {
r.HTML(200, "content", []interface{}{getPage(1)})
})
m.Get("/api/:id", func(params martini.Params, r render.Render) {
s := strings.Trim(params["id"], " .)(")
id := atoi(s)
r.JSON(200, getPage(id))
})
m.Get("/page/:id", func(params martini.Params, r render.Render) {
s := strings.Trim(params["id"], " .)(")
id := atoi(s)
r.HTML(200, "content", []interface{}{getPage(id)})
})
http.ListenAndServe("0.0.0.0:8000", m)
m.Run()
}
示例12: main
func main() {
m := martini.Classic()
// specify the layout to use when rendering HTML
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
// use the Mongo middleware
m.Use(DB())
// list of all cribs
m.Get("/", func(r render.Render, db *mgo.Database) {
r.HTML(200, "list", All(db))
})
/*
create a new crib the form submission. Contains some martini magic. The call
to binding.Form(Crib{}) parses out form data when the request comes in.
It binds the data to the struct, maps it to the request context and
injects into our next handler function to insert into Mongodb.
*/
m.Post("/", binding.Form(Crib{}), func(crib Crib, r render.Render, db *mgo.Database) {
db.C("cribs").Insert(crib)
r.HTML(200, "list", All(db))
})
// display the crib for a specific user
m.Get("/:handle", func(params martini.Params, r render.Render, db *mgo.Database) {
r.HTML(200, "display", Fetch(db, params["handle"]))
})
http.ListenAndServe(":8080", m)
}
示例13: main
func main() {
m := martini.Classic()
if os.Getenv("MARTINI_ENV") == "production" {
g.devMode = false
}
if g.IsDevMode() {
m.Use(runnerMiddleware)
}
g.InitDb()
m.Use(martini.Static("public/app"))
m.Use(func(resp http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, "/api/") {
token := req.Header.Get("AuthToken")
if token != "" {
n, err := g.Db().SelectInt(`select count(*) from users where token=$1`, token)
if err != nil && err != sql.ErrNoRows {
log.Fatalf(err.Error())
}
if n > 0 {
return
}
}
resp.WriteHeader(http.StatusUnauthorized)
resp.Write([]byte("You're not allowed to do this, sorry."))
}
})
m.Get("/", func(r http.ResponseWriter) {
t, err := template.ParseFiles("public/app/index.html")
if err != nil {
panic(err.Error())
}
t.Execute(r, nil)
})
m.Get("/auth", func(r http.ResponseWriter) {
username, token := makeRandomUserToken()
user := &biz.User{
Username: username,
Token: token,
Role: biz.RoleUser,
}
checkErr(g.Db().Insert(user))
resp, err := json.Marshal(map[string]interface{}{
"username": user.Username,
"token": user.Token,
})
checkErr(err)
r.Write(resp)
})
m.Get("/api/test", func(r http.ResponseWriter) {
r.Write([]byte("CLGT"))
})
m.Run()
}
示例14: Test_Logout
func Test_Logout(t *testing.T) {
recorder := httptest.NewRecorder()
s := sessions.NewCookieStore([]byte("secret123"))
m := martini.Classic()
m.Use(sessions.Sessions("my_session", s))
m.Use(Google(&Options{
// no need to configure
}))
m.Get("/", func(s sessions.Session) {
s.Set(keyToken, "dummy token")
})
m.Get("/get", func(s sessions.Session) {
if s.Get(keyToken) != nil {
t.Errorf("User credentials are still kept in the session.")
}
})
logout, _ := http.NewRequest("GET", "/logout", nil)
index, _ := http.NewRequest("GET", "/", nil)
m.ServeHTTP(httptest.NewRecorder(), index)
m.ServeHTTP(recorder, logout)
if recorder.Code != 302 {
t.Errorf("Not being redirected to the next page.")
}
}
示例15: main
func main() {
m := martini.Classic()
m.Get("/", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "image/jpeg")
err := jpeg.Encode(res, thumb(), &jpeg.Options{75})
if err != nil {
res.WriteHeader(500)
} else {
res.WriteHeader(200)
}
})
m.Get("/cached", func(response http.ResponseWriter, req *http.Request) {
response.Header().Set("Content-Type", "image/jpeg")
err := jpeg.Encode(response, preThumb(), &jpeg.Options{75})
if err != nil {
response.WriteHeader(500)
} else {
response.WriteHeader(200)
}
})
log.Fatal(http.ListenAndServe(":10010", m))
m.Run()
}