本文整理汇总了Golang中github.com/zenazn/goji/web.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
goji.Get("/", IndexHandler) // Doesn't need CSRF protection (no POST/PUT/DELETE actions).
signup := web.New()
goji.Handle("/signup/*", signup)
// But our signup forms do, so we add nosurf to their middleware stack (only).
signup.Use(nosurf.NewPure)
signup.Get("/signup/new", ShowSignupForm)
signup.Post("/signup/submit", SubmitSignupForm)
admin := web.New()
// A more advanced example: we enforce secure cookies (HTTPS only),
// set a domain and keep the expiry time low.
a := nosurf.New(admin)
a.SetBaseCookie(http.Cookie{
Name: "csrf_token",
Domain: "localhost",
Path: "/admin",
MaxAge: 3600 * 4,
HttpOnly: true,
Secure: true,
})
// Our /admin/* routes now have CSRF protection.
goji.Handle("/admin/*", a)
goji.Serve()
}
示例2: New
func New() *web.Mux {
mux := web.New()
mux.Get("/api/logins", handler.GetLoginList)
mux.Get("/api/stream/stdout/:id", handler.WsConsole)
mux.Get("/api/stream/user", handler.WsUser)
mux.Get("/api/auth/:host", handler.GetLogin)
mux.Post("/api/auth/:host", handler.GetLogin)
mux.Get("/api/badge/:host/:owner/:name/status.svg", handler.GetBadge)
mux.Get("/api/badge/:host/:owner/:name/cc.xml", handler.GetCC)
mux.Get("/api/hook/:host", handler.PostHook)
mux.Put("/api/hook/:host", handler.PostHook)
mux.Post("/api/hook/:host", handler.PostHook)
repos := web.New()
repos.Use(middleware.SetRepo)
repos.Use(middleware.RequireRepoRead)
repos.Use(middleware.RequireRepoAdmin)
repos.Get("/api/repos/:host/:owner/:name/branches/:branch/commits/:commit/console", handler.GetOutput)
repos.Get("/api/repos/:host/:owner/:name/branches/:branch/commits/:commit", handler.GetCommit)
repos.Post("/api/repos/:host/:owner/:name/branches/:branch/commits/:commit", handler.PostCommit)
repos.Get("/api/repos/:host/:owner/:name/commits", handler.GetCommitList)
repos.Get("/api/repos/:host/:owner/:name", handler.GetRepo)
repos.Put("/api/repos/:host/:owner/:name", handler.PutRepo)
repos.Post("/api/repos/:host/:owner/:name", handler.PostRepo)
repos.Delete("/api/repos/:host/:owner/:name", handler.DelRepo)
mux.Handle("/api/repos/:host/:owner/:name*", repos)
users := web.New()
users.Use(middleware.RequireUserAdmin)
users.Get("/api/users/:host/:login", handler.GetUser)
users.Post("/api/users/:host/:login", handler.PostUser)
users.Delete("/api/users/:host/:login", handler.DelUser)
users.Get("/api/users", handler.GetUserList)
mux.Handle("/api/users*", users)
user := web.New()
user.Use(middleware.RequireUser)
user.Get("/api/user/feed", handler.GetUserFeed)
user.Get("/api/user/repos", handler.GetUserRepos)
user.Get("/api/user", handler.GetUserCurrent)
user.Put("/api/user", handler.PutUser)
mux.Handle("/api/user*", user)
work := web.New()
work.Use(middleware.RequireUserAdmin)
work.Get("/api/work/started", handler.GetWorkStarted)
work.Get("/api/work/pending", handler.GetWorkPending)
work.Get("/api/work/assignments", handler.GetWorkAssigned)
work.Get("/api/workers", handler.GetWorkers)
work.Post("/api/workers", handler.PostWorker)
work.Delete("/api/workers", handler.DelWorker)
mux.Handle("/api/work*", work)
return mux
}
示例3: main
func main() {
admin := web.New()
admin.Use(middleware.SubRouter)
admin.Post("/login", login)
goji.Handle("/admin/*", admin)
dashboard := web.New()
dashboard.Use(auth)
dashboard.Use(middleware.SubRouter)
dashboard.Get("/json", sampleJsonHandle)
goji.Handle("/dashboard/*", dashboard)
goji.Use(middleware.Logger)
goji.Serve()
}
示例4: TestStoreCannotSave
// Tests for failure if the middleware can't save to the Store.
func TestStoreCannotSave(t *testing.T) {
s := web.New()
bs := &brokenSaveStore{}
s.Use(Protect(testKey, setStore(bs)))
s.Get("/", testHandler)
r, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
s.ServeHTTP(rr, r)
if rr.Code != http.StatusForbidden {
t.Fatalf("broken store did not set an error status: got %v want %v",
rr.Code, http.StatusForbidden)
}
if c := rr.Header().Get("Set-Cookie"); c != "" {
t.Fatalf("broken store incorrectly set a cookie: got %v want %v",
c, "")
}
}
示例5: TestUserCreateError
func TestUserCreateError(t *testing.T) {
count_before := 0
count_after := 0
m := web.New()
rooter(m)
ts := httptest.NewServer(m)
defer ts.Close()
db.Table("users").Count(&count_before)
values := url.Values{}
values.Add("Name", "エラー")
req, _ := http.NewRequest("POST", ts.URL+"/user/new", strings.NewReader(values.Encode()))
req.Header.Set("Authorization", "Basic dXNlcjp1c2Vy")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := new(http.Client)
response, _ := client.Do(req)
db.Table("users").Count(&count_after)
assert.Equal(t, 200, response.StatusCode)
assert.Equal(t, count_before, count_after)
}
示例6: New
func New() *web.Mux {
mux := web.New()
// Add routes to the global handler
mux.Get("/api/badges/:name/:number/channel/:channel/sdk/:sdk/status.svg", handler.GetBadge)
mux.Get("/api/badges/:name/:number/channel/:channel/status.svg", handler.GetBadge)
mux.Get("/api/packages/:name/:number/channel/:channel/sdk/:sdk/stdout.txt", handler.GetOutput)
mux.Get("/api/packages/:name/:number/channel/:channel/sdk/latest", handler.GetBuildLatest)
mux.Get("/api/packages/:name/:number/channel/:channel/sdk/:sdk", handler.GetBuild)
mux.Get("/api/channel/:channel", handler.GetChannel)
mux.Get("/api/feed", handler.GetFeed)
// Add routes for querying the build queue (workers)
mux.Get("/api/work/started", handler.GetWorkStarted)
mux.Get("/api/work/pending", handler.GetWorkPending)
mux.Get("/api/work/assignments", handler.GetWorkAssigned)
mux.Get("/api/workers", handler.GetWorkers)
// Restricted operations
mux.Delete("/sudo/api/workers/:id", handler.DelWorker)
mux.Post("/sudo/api/workers", handler.PostWorker)
mux.Post("/sudo/api/build", handler.PostBuild)
// Main Pages
mux.Get("/:name/:number/:channel/:sdk", handler.GetBuildPage)
mux.Get("/:name/:number/:channel", handler.GetBuildPage)
mux.Get("/", handler.GetHomePage)
return mux
}
示例7: main
func main() {
// Initalize database.
ExecuteSchemas()
// Serve static files.
staticDirs := []string{"bower_components", "res"}
for _, d := range staticDirs {
static := web.New()
pattern, prefix := fmt.Sprintf("/%s/*", d), fmt.Sprintf("/%s/", d)
static.Get(pattern, http.StripPrefix(prefix, http.FileServer(http.Dir(d))))
http.Handle(prefix, static)
}
goji.Use(applySessions)
goji.Use(context.ClearHandler)
goji.Get("/", handler(serveIndex))
goji.Get("/login", handler(serveLogin))
goji.Get("/github_callback", handler(serveGitHubCallback))
// TODO(samertm): Make this POST /user/email.
goji.Post("/save_email", handler(serveSaveEmail))
goji.Post("/group/create", handler(serveGroupCreate))
goji.Post("/group/:group_id/refresh", handler(serveGroupRefresh))
goji.Get("/group/:group_id/join", handler(serveGroupJoin))
goji.Get("/group/:group_id", handler(serveGroup))
goji.Get("/group/:group_id/user/:user_id/stats.svg", handler(serveUserStatsSVG))
goji.Serve()
}
示例8: initRoutes
func initRoutes() {
// Setup static files
static := web.New()
static.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
http.Handle("/static/", static)
// prepare routes, get/post stuff etc
goji.Get("/", startPage)
goji.Post("/held/action/:action/*", runActionAndRedirect)
goji.Post("/held/complexaction", runComplexActionAndRedirect)
goji.Post("/held/save", saveHeld)
goji.Get("/held/isValid", isValid)
// partial html stuff - sub-pages
goji.Get("/held/page/new", pageNew)
goji.Get("/held/page/modEigenschaften", pageModEigenschaften)
goji.Get("/held/page/selectKampftechniken", pageSelectKampftechiken)
goji.Get("/held/page/allgemeines", pageAllgemeines)
goji.Get("/held/page/professionsAuswahl", pageAuswahlProfession)
goji.Get("/held/page/kampftechniken", pageKampftechniken)
goji.Get("/held/page/talente", pageTalente)
goji.Get("/held/page/footer", pageFooter)
goji.Get("/held/page/karmales", pageLiturgien)
goji.Get("/held/page/magie", pageZauber)
// json-accessors/ partial rest-API?
goji.Get("/held/data/ap", getAP)
}
示例9: TestTemplateField
func TestTemplateField(t *testing.T) {
s := web.New()
CSRF := Protect(
testKey,
FieldName(testFieldName),
)
s.Use(CSRF)
var token string
var customTemplateField string
s.Handle("/", web.HandlerFunc(func(c web.C, w http.ResponseWriter, r *http.Request) {
token = Token(c, r)
customTemplateField = string(TemplateField(c, r))
}))
r, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
s.ServeHTTP(rr, r)
expectedTemplateField := fmt.Sprintf(testTemplateField, testFieldName, token)
if customTemplateField != expectedTemplateField {
t.Fatalf("templateField not set correctly: got %v want %v",
customTemplateField, expectedTemplateField)
}
}
示例10: TestFormToken
// Test that our form helpers correctly inject a token into the response body.
func TestFormToken(t *testing.T) {
s := web.New()
s.Use(Protect(testKey))
// Make the token available outside of the handler for comparison.
var token string
s.Get("/", web.HandlerFunc(func(c web.C, w http.ResponseWriter, r *http.Request) {
token = Token(c, r)
t := template.Must((template.New("base").Parse(testTemplate)))
t.Execute(w, map[string]interface{}{
TemplateTag: TemplateField(c, r),
})
}))
r, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
s.ServeHTTP(rr, r)
if rr.Code != http.StatusOK {
t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
rr.Code, http.StatusOK)
}
if len(token) != base64.StdEncoding.EncodedLen(tokenLength*2) {
t.Fatalf("token length invalid: got %v want %v", len(token), base64.StdEncoding.EncodedLen(tokenLength*2))
}
if !strings.Contains(rr.Body.String(), token) {
t.Fatalf("token not in response body: got %v want %v", rr.Body.String(), token)
}
}
示例11: getServerInstance
func getServerInstance() *httptest.Server {
api := NewApi()
mux := web.New()
api.Route(mux)
return httptest.NewServer(mux)
}
示例12: main
func main() {
awsSession := session.New()
awsSession.Config.WithRegion(os.Getenv("AWS_REGION"))
tree = &dynamotree.Tree{
TableName: "hstore-example-shortlinks",
DB: dynamodb.New(awsSession),
}
err := tree.CreateTable()
if err != nil {
log.Fatalf("hstore: %s", err)
}
goji.Get("/:link", ServeLink)
goji.Post("/signup", CreateAccount)
authMux := web.New()
authMux.Use(RequireAccount)
authMux.Post("/", CreateLink)
authMux.Get("/", ListLinks)
authMux.Delete("/:link", DeleteLink) // TODO(ross): this doesn't work (!)
goji.Handle("/", authMux)
goji.Serve()
}
示例13: NewRouter
func NewRouter(b *backend.Backend) {
router = Router{
Backend: b,
}
goji.Get("/ping", router.Ping)
api := web.New()
goji.Handle("/v1/*", api)
api.Get("/overview", router.Overview)
api.Get("/accounts", router.ShowAccount)
api.Get("/accounts/:account_id", router.ShowAccount)
api.Get("/categories", router.ShowCategory)
api.Get("/categories/:category_id", router.ShowCategory)
api.Post("/transaction", router.NewTransaction)
api.Post("/account", router.NewAccount)
api.Post("/category", router.NewCategory)
api.Put("/transaction/:transaction_id", router.UpdateTransaction)
api.Put("/account/:account_id", router.UpdateAccount)
api.Put("/category/:category_id", router.UpdateCategory)
api.Delete("/transaction/:transaction_id", router.DeleteTransaction)
api.Delete("/account/:account_id", router.DeleteAccount)
api.Delete("/category/:category_id", router.DeleteCategory)
api.Use(goji.DefaultMux.Router)
api.Use(middleware.SubRouter)
}
示例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: BenchmarkGoji_Middleware
func BenchmarkGoji_Middleware(b *testing.B) {
middleware := func(h http.Handler) http.Handler {
handler := func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
return http.HandlerFunc(handler)
}
m := gojiweb.New()
m.Get("/action", gojiHelloHandler)
m.Use(middleware)
m.Use(middleware)
m.Use(middleware)
m.Use(middleware)
m.Use(middleware)
m.Use(middleware)
rw, req := testRequest("GET", "/action")
b.ResetTimer()
for i := 0; i < b.N; i++ {
m.ServeHTTP(rw, req)
if rw.Code != 200 {
panic("goji: no good")
}
}
}