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) }
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() }
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 }
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 }
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) } }
//初始化并启动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) } } // }}}
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) }
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) } }
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") } }
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) }
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 }
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()) } }
func main() { m := martini.Classic() m.Use(MapEncoder) m.Get("/server/:ip", GetServerDetails) m.Get("/servers", GetServers) m.Run() }
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") }
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() }
func main() { m := martini.Classic() m.Use(render.Renderer(render.Options{ Directory: "templates", Extensions: []string{".tmpl", ".html"}, Charset: "UTF-8", Funcs: []template.FuncMap{ { "equal": func(args ...interface{}) bool { return args[0] == args[1] }, }, }, })) store := sessions.NewCookieStore([]byte("secret123")) m.Use(sessions.Sessions("my_session", store)) m.Get("/", youth) m.Get("/firtConfirm", firtConfirm) m.Post("/firtConfirm", binding.Form(model.User{}), firtConfirmPost) m.Post("/userSiginCheck", binding.Bind(SiginIfo{}), userSiginCheck) m.Get("/userInforEdit", userInforEdit) m.Post("/userInforEdit", binding.Form(model.User{}), userInforEditPost) m.Get("/editReruenInfo/:status", editReruenInfo) m.Run() }
func Test_LogoutOnAccessTokenExpiration(t *testing.T) { recorder := httptest.NewRecorder() s := sessions.NewCookieStore([]byte("secret123")) m := martini.Classic() m.Use(sessions.Sessions("my_session", s)) m.Use(Google( &oauth2.Config{ ClientID: "client_id", ClientSecret: "client_secret", RedirectURL: "redirect_url", }, )) m.Get("/addtoken", func(s sessions.Session) { s.Set(keyToken, "dummy token") }) m.Get("/", func(s sessions.Session) { if s.Get(keyToken) != nil { t.Errorf("User not logged out although access token is expired.") } }) addtoken, _ := http.NewRequest("GET", "/addtoken", nil) index, _ := http.NewRequest("GET", "/", nil) m.ServeHTTP(recorder, addtoken) m.ServeHTTP(recorder, index) }
func Test_GenerateCustomHeader(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, Header: "X-SEESurfToken", })) // 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")) m.ServeHTTP(res2, req2) if res2.Header().Get("X-SEESurfToken") == "" { t.Error("Failed to set X-SEESurfToken custom header") } }
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( &oauth2.Config{ ClientID: "client_id", ClientSecret: "client_secret", RedirectURL: "redirect_url", }, )) 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.") } }
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") } }
func main() { m := martini.Classic() m.Router.Get("/", func(req *http.Request, w martini.ResponseWriter) (int, string) { return 200, "Hello Jerry!" }) m.Run() }
func Test_GenerateCustomCookie(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", SetCookie: true, Cookie: "seesurf", })) // Simulate login. m.Get("/login", func(s sessions.Session) string { s.Set("userID", "123456") return "OK" }) // Generate cookie. 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")) m.ServeHTTP(res2, req2) if !strings.Contains(res2.Header().Get("Set-Cookie"), "seesurf") { t.Error("Failed to set custom csrf cookie") } }
func testJson(t *testing.T, withInterface bool) { for index, test := range jsonTests { recorder := httptest.NewRecorder() handler := func(post BlogPost, errors Errors) { handle(test, t, index, post, errors) } binding := Json(BlogPost{}) if withInterface { handler = func(post BlogPost, errors Errors) { post.Create(test, t, index) } binding = Bind(BlogPost{}, (*Modeler)(nil)) } 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) } }
func Routes() http.Handler { // Middlewares are setup and run before each incoming request // the ones named like *Provider provide singleton instances // of injectable objects. For instance appx, logger, appengine context // can be injected in our routes handlers (a.k.a controllers) router := martini.Classic() router.Use(render.Renderer()) router.Use(middlewares.AppengineContextProvider) router.Use(middlewares.LoggerProvider) router.Use(middlewares.AppxProvider) router.Post("/login", binding.Bind(controllers.LoginForm{}), controllers.Login) router.Group("/account", func(r martini.Router) { r.Post("/registerDropbox", binding.Bind(controllers.RegisterDropboxForm{}), controllers.RegisterDropbox) r.Post("/update", binding.Bind(controllers.AccountUpdateForm{}), controllers.UpdateAccount) r.Group("/dropbox", func(r martini.Router) { r.Post("/init", controllers.DropboxInit) r.Post("/delta", controllers.DropboxDelta) }, middlewares.ExternalServiceAuthorizationProvider) r.Group("/trails", func(r martini.Router) { r.Get("/next_evaluation", controllers.TrailNextEvaluation) r.Patch("/:trail_id/like", controllers.TrailLike) r.Patch("/:trail_id/dislike", controllers.TrailDislike) r.Get("/tags", controllers.Tags) r.Get("/tags/:tag_id", controllers.TagTrails) }) }, middlewares.AuthorizationAccountProvider) return router }
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) } }
func main() { log.Println("server start11") fmt.Printf("access_token:%s", ACCESS_TOKEN) m := martini.Classic() m.Handlers(martini.Recovery()) m.Use(render.Renderer(render.Options{ Extensions: []string{".html", ".shtml"}, })) m.Get("/", checkSignatureHandler) m.Post("/", transceiverMsgHandler) m.Get("/createMenu", createMenuHandler) m.Get("/hi", func() string { return "Hello world!" }) http.Handle("/", m) if martini.Env == martini.Dev { HOST = ":8080" } else { HOST = ":80" } log.Printf("start web server on %s", HOST) http.ListenAndServe(HOST, nil) }
func TestMultipartMultipleFileForm(t *testing.T) { for testIdx, tc := range multifileTests { req := buildFormFileReq(t, &tc) recorder := httptest.NewRecorder() handler := func(fup MultipleFileUpload, errors Errors) { // expecting everything to succeed if errors.Count() > 0 { t.Errorf("Expected no errors, got: %+v", errors) } assertEqualField(t, "Title", testIdx, tc.title, fup.Title) if len(tc.documents) != len(fup.Document) { t.Errorf("Expected %d documents, got: %+v", len(tc.documents), fup.Document) } for i, tcDocument := range tc.documents { if (fup.Document[i] == nil) != tcDocument.isNil { t.Errorf("Expected document.isNil: %+v, got %+v", tcDocument.isNil, fup.Document[i]) } if fup.Document[i] != nil { assertEqualField(t, "Filename", testIdx, tcDocument.fileName, fup.Document[i].Filename) uploadData := unpackFileHeaderData(fup.Document[i], t) assertEqualField(t, "Document Data", testIdx, tcDocument.data, uploadData) } } } m := martini.Classic() m.Post(fileroute, MultipartForm(MultipleFileUpload{}), handler) m.ServeHTTP(recorder, req) } }
func main() { m := martini.Classic() m.Map(SetupDB()) m.Get("/", func() string { return "Hello world!" }) m.Get("/projects", func(rw http.ResponseWriter, r *http.Request, db *sql.DB) { rows, err := db.Query("SELECT id, title, description, shares, target, buyers, posted, price FROM proj") PanicIf(err) defer rows.Close() var id, buyers, posted int var title, description string var shares, target, price float32 projList := []proj{} for rows.Next() { PanicIf(rows.Err()) err := rows.Scan(&id, &title, &description, &shares, &target, &buyers, &posted, &price) PanicIf(err) Proj := proj{ID: id, Title: title, Description: description, Shares: shares, Target: target, Buyers: buyers, Posted: posted, Price: price} projList = append(projList, Proj) } JASONpls := projects{Projects: projList} b, err := json.Marshal(JASONpls) PanicIf(err) fmt.Fprintf(rw, string(b)) }) m.Run() }
func main() { kingpin.Version("0.0.1") kingpin.Parse() config := Config{ Server: *server, Database: *database, Interval: *interval, Debug: *debug, Port: ":" + *port, } if config.Debug { log.Printf("Booting with config: %+v\n", config) } updates := make(chan State) state := map[string]State{} go cacheState(updates, state) go submitCachedState(state, config) m := martini.Classic() m.Group("/state", func(r martini.Router) { r.Post("", func(res http.ResponseWriter, req *http.Request) { CreateState(updates, res, req) }) r.Get("", func() []byte { data, _ := json.Marshal(state) return data }) }) log.Fatal(http.ListenAndServe(config.Port, m)) }
func main() { defer clean() mck := shardmaster.MakeClerk(smh) mck.Join(gids[0], ha[0]) ck.Subscribe("a") ck.Subscribe("b") ck.Subscribe("c") ck.Subscribe("d") ck.Subscribe("e") defer cleanupClerk(ck) go listener(ck) go h.run() m := martini.Classic() m.Use(render.Renderer()) m.Get("/", func(r render.Render) { r.HTML(200, "index", "") }) m.Get("/ws", wsHandler) m.Run() }