當前位置: 首頁>>代碼示例>>Golang>>正文


Golang martini.Classic函數代碼示例

本文整理匯總了Golang中github.com/go-martini/martini.Classic函數的典型用法代碼示例。如果您正苦於以下問題:Golang Classic函數的具體用法?Golang Classic怎麽用?Golang Classic使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Classic函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: init

func init() {
	//Separate apis because use different middleware to authenticate requests... might be a better way to handle this
	publicApi := martini.Classic()
	publicApi.Use(apps.ResolveApp)

	privateApi := martini.Classic()

	apps.RegisterWebService(privateApi)
	keys.RegisterWebService(publicApi)

	http.Handle("/api/v1/", publicApi)
	http.Handle("/", privateApi)
}
開發者ID:kurtinlane,項目名稱:submarine,代碼行數:13,代碼來源:server.go

示例2: StartServer

func StartServer() {

	m := martini.Classic()

	m.Use(render.Renderer())

	db_session := getSession()
	if db_session == nil {
		return
	}

	user, err := controllers.NewUserController(db_session.C("users"))
	if err != nil {
		log.Error("Error reading mongo db users collection: ", err)
		return
	}

	// m.GET("/", user.Home)
	//  dashboard or landing page for app   root_path  "/"

	m.Group("/users", func(r martini.Router) {
		r.Get("", user.GetAllUsers)
		r.Post("", user.CreateUser)
		// r.Get("/(?P<name>[a-zA-Z]+)", user.GetUser)    //get user's profile
		r.Get("/:id", user.GetUser)
		r.Delete("/:id", user.DeleteUser)
		r.Put("/:id", user.UpdateUser)
		// r.Delete("/(?P<name>[a-zA-Z]+)", user.DeleteUser) //delete user's profile and associations
		// r.Patch("/(?P<name>[a-zA-Z]+)", user.UpdateUser) //update user's profile
	})

	m.Run()

}
開發者ID:4nthem,項目名稱:State,代碼行數:34,代碼來源:server.go

示例3: NewWeb

func NewWeb(mailConf *conf.MailConf, debug bool) *MailWeb {
	var web *MailWeb = new(MailWeb)
	web.mconf = mailConf
	web.debug = debug
	web.userTimeout = 86400 // 1 day

	store := sessions.NewCookieStore(securecookie.GenerateRandomKey(128))
	// 1) Set a maximum age for the client-side cookies (forces a session timeout afterwards)
	store.Options(sessions.Options{MaxAge: int(web.userTimeout)})

	web.martini = martini.Classic()
	web.martini.Use(render.Renderer(render.Options{
		Directory:  "static/templates",
		Extensions: []string{".html"},
	}))
	web.martini.Use(sessions.Sessions("watneySession", store))
	web.martini.Use(sessionauth.SessionUser(auth.GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/sessionTimeout"
	sessionauth.RedirectParam = "next"

	// 2) Register a cleanup go routine that checks every x minutes, for outdated users, which
	//	  simply left the page without logging out
	web.registerUserCleanup(30)

	// x) Define and set all handlers
	web.initHandlers()
	return web
}
開發者ID:mdrobek,項目名稱:watney,代碼行數:28,代碼來源:web.go

示例4: testMultipart

func testMultipart(t *testing.T, test testCase, middleware martini.Handler, handler martini.Handler, index int) *httptest.ResponseRecorder {
	recorder := httptest.NewRecorder()

	m := martini.Classic()
	m.Post(route, middleware, handler)

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	writer.WriteField("title", test.ref.Title)
	writer.WriteField("content", test.ref.Content)
	writer.WriteField("views", strconv.Itoa(test.ref.Views))
	if len(test.ref.Multiple) != 0 {
		for _, value := range test.ref.Multiple {
			writer.WriteField("multiple", strconv.Itoa(value))
		}
	}

	req, err := http.NewRequest(test.method, test.path, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())

	if err != nil {
		t.Error(err)
	}

	err = writer.Close()
	if err != nil {
		t.Error(err)
	}

	m.ServeHTTP(recorder, req)

	return recorder
}
開發者ID:joshk,項目名稱:hustle,代碼行數:33,代碼來源:binding_test.go

示例5: 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)
	}
}
開發者ID:joshk,項目名稱:hustle,代碼行數:25,代碼來源:binding_test.go

示例6: StartManager

//初始化並啟動web服務
func StartManager(sl *schedule.ScheduleManager) { // {{{
	g = sl.Global
	m := martini.Classic()
	m.Use(Logger)
	m.Use(martini.Static("web/public"))
	m.Use(web.ContextWithCookieSecret(""))
	m.Use(render.Renderer(render.Options{
		Directory:       "web/templates",            // Specify what path to load the templates from.
		Extensions:      []string{".tmpl", ".html"}, // Specify extensions to load for templates.
		Delims:          render.Delims{"{[{", "}]}"},
		Charset:         "UTF-8",     // Sets encoding for json and html content-types. Default is "UTF-8".
		IndentJSON:      true,        // Output human readable JSON
		IndentXML:       true,        // Output human readable XML
		HTMLContentType: "text/html", // Output XHTML content type instead of default "text/html"
	}))

	m.Map(sl)
	controller(m)

	g.L.Println("Web manager is running in ", g.ManagerPort)
	err := http.ListenAndServe(g.ManagerPort, m)
	if err != nil {
		log.Fatal("Fail to start server: %v", err)
	}
} // }}}
開發者ID:rprp,項目名稱:hivego,代碼行數:26,代碼來源:manager.go

示例7: Start

func Start(port string, onStart func()) {

	// Logging init
	flag.Set("log_dir", utils.GetRuntimeDir(config.GetString("log_dir")))
	flag.Set("alsologtostderr", "true")
	flag.Parse()
	defer glog.Flush()

	m := martini.Classic()
	m.Use(render.Renderer(render.Options{
		Charset:   "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8".
		Delims:    render.Delims{"${", "}"},
		Directory: utils.GetRuntimeDir("resources/views"),
	}))

	m.Use(martini.Static(utils.GetRuntimeDir("public")))
	controller.MappingController(m)

	http.Handle("/rpc", rpc.GetServer())
	http.Handle("/", m)

	if db.IsConnected() {
		defer db.Close()
	}

	onStart()

	for _, fn := range methods {
		go fn()
	}

	http.ListenAndServe(":"+port, nil)
}
開發者ID:sdgdsffdsfff,項目名稱:svnmanager,代碼行數:33,代碼來源:bootstrap.go

示例8: 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(
		&oauth2.Config{
			ClientID:     "client_id",
			ClientSecret: "client_secret",
			Scopes:       []string{"x", "y"},
			RedirectURL:  "redirect_url",
		},
	))
	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)
	}
}
開發者ID:cyberwolf88,項目名稱:oauth2,代碼行數:25,代碼來源:oauth2_test.go

示例9: Test_OriginHeader

func Test_OriginHeader(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",
		SetHeader:  true,
	}))

	// Simulate login.
	m.Get("/login", func(s sessions.Session) string {
		s.Set("userID", "123456")
		return "OK"
	})

	// Generate HTTP header.
	m.Get("/private", func(s sessions.Session, x CSRF) string {
		return "OK"
	})

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/private", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	req2.Header.Set("Origin", "https://www.example.com")
	m.ServeHTTP(res2, req2)

	if res2.Header().Get("X-CSRFToken") != "" {
		t.Error("X-CSRFToken present in cross origin request")
	}
}
開發者ID:unrolled,項目名稱:csrf,代碼行數:35,代碼來源:csrf_test.go

示例10: mount

func mount(war string) {

	m := martini.Classic()
	m.Handlers(martini.Recovery())
	m.Use(gzip.All())
	m.Use(martini.Static(war, martini.StaticOptions{SkipLogging: true}))
	//    m.Use(render.Renderer(render.Options{
	//        Extensions: []string{".html", ".shtml"},
	//    }))
	//	m.Use(render.Renderer())
	//    m.Use(midTextDefault)

	//map web
	m.Use(func(w http.ResponseWriter, c martini.Context) {
		web := &Web{w: w}
		c.Map(web)
	})

	m.Group("/test", func(api martini.Router) {
		api.Get("", mainHandler)
		api.Get("/1", test1Handler)
		api.Get("/2", test2Handler)
	})

	http.Handle("/", m)
}
開發者ID:gavinzhs,項目名稱:laohuo_process,代碼行數:26,代碼來源:mount.go

示例11: main

func main() {
	fmt.Println("jøkulhlaup ", Version)

	r := render.New(render.Options{})

	m := martini.Classic()

	fizz := fizz.New()

	// Dashboard
	m.Get("/", func(w http.ResponseWriter, req *http.Request) {
		data := map[string]string{
			"title":  "Jøkulhlaup",
			"imgsrc": "img/jøkulhlaup.png",
			"width":  "1440",
			"height": "900",
		}

		// !! Reload template !!
		//r = render.New(render.Options{})

		// Render the specified templates/.tmpl file as HTML and return
		r.HTML(w, http.StatusOK, "black", data)
	})

	// Activate the permission middleware
	m.Use(fizz.All())

	// Share the files in static
	m.Use(martini.Static("static"))

	m.Run() // port 3000 by default
}
開發者ID:xyproto,項目名稱:jokulhlaup,代碼行數:33,代碼來源:main.go

示例12: 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())
	}
}
開發者ID:heroku,項目名稱:sproxy,代碼行數:25,代碼來源:basic_test.go

示例13: main

func main() {
	m := martini.Classic()
	m.Use(MapEncoder)
	m.Get("/server/:ip", GetServerDetails)
	m.Get("/servers", GetServers)
	m.Run()
}
開發者ID:kidoman,項目名稱:server-browser,代碼行數:7,代碼來源:main.go

示例14: runTestServer

func runTestServer() {
	m := martini.Classic()
	m.Get("/get", func() (int, string) {
		return 200, EXPECTED_GET_RESULT
	})
	m.Post("/post_json", func(res http.ResponseWriter, req *http.Request) (int, string) {
		body, _ := ioutil.ReadAll(req.Body)
		var fake fakeJSON
		err := json.Unmarshal(body, &fake)
		if err != nil {
			return 500, ERROR
		}
		return 202, EXPECTED_POST_RESULT
	})
	m.Post("/post_pb", func(res http.ResponseWriter, req *http.Request) (int, string) {
		body, _ := ioutil.ReadAll(req.Body)
		fake := &mesosproto.FrameworkID{}
		err := proto.Unmarshal(body, fake)
		if err != nil {
			return 500, ERROR
		}
		return 202, EXPECTED_POST_RESULT
	})
	m.RunOnAddr(":22334")
}
開發者ID:layer-x,項目名稱:layerx-commons,代碼行數:25,代碼來源:httpclient_test.go

示例15: main

func main() {

	// Initialize
	m := martini.Classic()

	// Connect to mongo
	m.Use(middlewares.Connect())

	// Templating support
	m.Use(middlewares.Templates())

	// Routes

	m.Get("/", func(r render.Render) {
		r.Redirect("/available")
	})

	m.Group("/available", func(r martini.Router) {
		r.Get("", available.List)
		r.Get("/new", available.New)
		r.Get("/:_id", available.Edit)
		r.Post("", binding.Bind(models.AvailableTopic{}), available.Create)
		r.Post("/:_id", binding.Bind(models.AvailableTopic{}), available.Update)
		r.Delete("/:_id", available.Delete)
	})

	// Start listening
	m.Run()
}
開發者ID:gitter-badger,項目名稱:khabar-admin,代碼行數:29,代碼來源:main.go


注:本文中的github.com/go-martini/martini.Classic函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。