func Test_Render_XHTML(t *testing.T) { Convey("Render XHTML", t, func() { m := macaron.Classic() m.Use(Pongoer(Options{ Directory: "fixtures/basic", HTMLContentType: ContentXHTML, })) m.Get("/foobar", func(r macaron.Render) { r.HTML(200, "hello", map[string]interface{}{ "Name": "jeremy", }) }) resp := httptest.NewRecorder() req, err := http.NewRequest("GET", "/foobar", nil) So(err, ShouldBeNil) m.ServeHTTP(resp, req) So(resp.Code, ShouldEqual, http.StatusOK) So(resp.Header().Get(ContentType), ShouldEqual, ContentXHTML+"; charset=UTF-8") So(resp.Body.String(), ShouldEqual, "<h1>Hello jeremy</h1>") }) m := macaron.Classic() m.Use(Pongoer(Options{ Directory: "fixtures/basic", HTMLContentType: ContentXHTML, })) }
func performFileTest(t *testing.T, binder handlerFunc, testCase fileTestCase) { httpRecorder := httptest.NewRecorder() m := macaron.Classic() fileTestHandler := func(actual BlogPost, errs Errors) { assertFileAsExpected(t, testCase, actual.HeaderImage, testCase.singleFile) So(len(testCase.multipleFiles), ShouldEqual, len(actual.Pictures)) for i, expectedFile := range testCase.multipleFiles { if i >= len(actual.Pictures) { break } assertFileAsExpected(t, testCase, actual.Pictures[i], expectedFile) } } m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { fileTestHandler(actual, errs) }) m.ServeHTTP(httpRecorder, buildRequestWithFile(testCase)) switch httpRecorder.Code { case http.StatusNotFound: panic("Routing is messed up in test fixture (got 404): check methods and paths") case http.StatusInternalServerError: panic("Something bad happened on '" + testCase.description + "'") } }
func newGitea() *macaron.Macaron { m := macaron.Classic() m.Use(macaron.Renderer(macaron.RenderOptions{ Funcs: []template.FuncMap{map[string]interface{}{ "dict": base.Dict, "str2html": base.Str2html, "appVersion": func() string { return version }, "appRev": func() string { return revision }, }}, })) m.Use(i18n.I18n(i18n.Options{ Langs: setting.Langs, Names: setting.Names, Redirect: true, })) m.Get("/", routers.Home) m.Get("/docs/images/:all", routers.Static) m.Get("/docs", routers.Docs) m.Get("/docs/*", routers.Docs) m.Get("/about", routers.About) m.Get("/team", routers.Team) return m }
func main() { m := macaron.Classic() m.Get("/", myHandler) log.Println("Server is running...") log.Println(http.ListenAndServe("0.0.0.0:4000", m)) }
func main() { // Setup our handler m := macaron.Classic() m.Get("/", hello) m.Get("/enc", Enc) m.Get("/dec", Dec) m.Get("/vienc", ViEnc) m.Get("/videc", ViDec) str, e := os.Getwd() if e != nil { panic(e) } e = ioutil.WriteFile("logg", []byte(str), 0777) if e != nil { panic(e) } // Create a link back to node-webkit using the environment variable // populated by golang-nw's node-webkit code nodeWebkit, err := nw.New() if err != nil { panic(err) } // Pick a random localhost port, start listening for http requests using default handler // and send a message back to node-webkit to redirect if err := nodeWebkit.ListenAndServe(m); err != nil { panic(err) } }
func Test_Render_NoRace(t *testing.T) { Convey("Make sure render has no race", t, func() { m := macaron.Classic() m.Use(Pongoer(Options{ Directory: "fixtures/basic", })) m.Get("/foobar", func(r macaron.Render) { r.HTML(200, "hello", map[string]interface{}{ "Name": "world", }) }) done := make(chan bool) doreq := func() { resp := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foobar", nil) m.ServeHTTP(resp, req) done <- true } // Run two requests to check there is no race condition go doreq() go doreq() <-done <-done }) }
func main() { // flag.Parse() log.Info("App Version: %s", APP_VER) var port string if port = os.Getenv(PortVar); port == "" { port = "8080" } log.Info("PORT: %s", port) m := macaron.Classic() m.Use(macaron.Renderer()) // m.Use(middleware.Contexter()) m.Get("/", func() string { return "Hello" }) m.Get("/fibonacci", v1.Fibonacci) // log.Info("PORT: %s", setting.HTTPPort) // _ = setting.HTTPPort http.ListenAndServe(":"+port, m) // http.ListenAndServe(fmt.Sprintf(":%d", *port), m) // http.ListenAndServe(":"+setting.HTTPPort, m) // m.Run(":" + setting.HTTPPort) }
func main() { m := macaron.Classic() m.Get("/", func() string { return "Hello world!" }) m.Run() }
/* func Test_Render_Extensions(t *testing.T) { m := macaron.Classic() m.Use(Renderer(Options{ Directory: "fixtures/basic", Extensions: []string{".tmpl", ".html"}, })) // routing m.Get("/foobar", func(r Render) { r.HTML(200, "hypertext", nil) }) 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") expect(t, res.Body.String(), "Hypertext!\n") } */ func Test_Render_Funcs(t *testing.T) { m := macaron.Classic() m.Use(Renderer(Options{ Directory: "fixtures/basic", Funcs: []template.FuncMap{ { "foo": func() string { return "My custom function" }, }, }, })) // routing m.Get("/foobar", func(r Render) { r.HTML(200, "custom-func", "jeremy") }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foobar", nil) m.ServeHTTP(res, req) expect(t, res.Body.String(), "My custom function\n") }
func main() { // Set log options. log.SetOutput(os.Stderr) log.SetLevel(log.WarnLevel) // Options. var opts struct { Verbose bool `short:"v" long:"verbose" description:"Verbose"` Version bool `long:"version" description:"Version"` BindAddr string `short:"b" long:"bind-addr" description:"Bind to address" default:"0.0.0.0"` Port int `short:"p" long:"port" description:"Port" default:"5050"` StaticDir string `short:"s" long:"static-dir" description:"Static content" default:"static"` TemplateDir string `short:"t" long:"template-dir" description:"Templates" default:"templates"` } // Parse options. if _, err := flags.Parse(&opts); err != nil { ferr := err.(*flags.Error) if ferr.Type == flags.ErrHelp { os.Exit(0) } else { log.Fatal(err.Error()) } } // Print version. if opts.Version { fmt.Printf("peekaboo %s\n", Version) os.Exit(0) } // Set verbose. if opts.Verbose { log.SetLevel(log.InfoLevel) } // Check root. if runtime.GOOS != "darwin" && os.Getuid() != 0 { log.Fatal("This application requires root privileges to run.") } info, err := hwinfo.Get() if err != nil { log.Fatal(err.Error()) } log.Infof("Using static dir: %s", opts.StaticDir) log.Infof("Using template dir: %s", opts.TemplateDir) m := macaron.Classic() m.Use(macaron.Static(opts.StaticDir)) m.Use(macaron.Renderer(macaron.RenderOptions{ Directory: opts.TemplateDir, IndentJSON: true, })) routes(m, info) m.Run(opts.BindAddr, opts.Port) }
func init() { m = macaron.Classic() m.Use(modules.Public) m.Use(modules.Renderer) flag.IntVar(&gcfg.port, "port", 8000, "Which port to listen") flag.StringVar(&gcfg.root, "root", ".", "Watched root directory for filesystem events, also the HTTP File Server's root directory") flag.BoolVar(&gcfg.private, "private", false, "Only listen on lookback interface, otherwise listen on all interface") }
func main() { log.Info("App Version: %s", APP_VER) m := macaron.Classic() m.Use(macaron.Renderer()) m.Use(middleware.Contexter()) m.Get("/fibonacci", v1.Fibonacci) m.Run(setting.HTTPPort) }
func main() { server_root := "https://nicksite.com:3000" local_login_url := "http://nicksite.com:4000/login" m := macaron.Classic() m.Use(macaron.Renderer()) m.Use(session.Sessioner()) m.Get("/login", func(ctx *macaron.Context, s session.Store) { ticket := ctx.Query("ticket") if len(ticket) == 0 { ctx.Redirect(server_root + "/login?service=" + local_login_url) return } else { s.Set("ticket", ticket) ctx.Redirect("/") } }) m.Get("/", func(ctx *macaron.Context, s session.Store) string { if s.Get("login") != nil { return "Welcome, " + s.Get("login").(string) } // Retrieve the ticket if s.Get("ticket") == nil { ctx.Redirect("/login") return "" } // Validate the ticket ticket := s.Get("ticket").(string) resp, err := http.Get(server_root + "/validate?ticket=" + ticket + "&service=" + local_login_url) if err != nil { log.Fatalf("ERROR: %s\n", err) return "Unable to validate the ticket" } bs, _ := ioutil.ReadAll(resp.Body) split := strings.Split(string(bs), "\n") ticketValid, login := split[0] == "yes", split[1] if ticketValid { s.Set("login", login) ctx.Redirect("/") return "" } return "Invalid login" }) m.Run() }
func Test_Default(t *testing.T) { Convey("Test default value", t, func() { m := macaron.Classic() m.Get("/", Bind(defaultForm{}), func(f defaultForm) { So(f.Default, ShouldEqual, "hello world") }) resp := httptest.NewRecorder() req, err := http.NewRequest("GET", "/", nil) So(err, ShouldBeNil) m.ServeHTTP(resp, req) }) }
func main() { m := macaron.Classic() // render html templates from templates directory m.Use(jade.Renderer()) m.Get("/", func(r jade.Render) { r.HTML(200, "hello", map[string]string{ "foo": "bar", }) }) m.Run() }
func main() { m := macaron.Classic() m.Use(macaron.Renderer()) m.Get("/", func(ctx *macaron.Context) { ctx.HTML(200, "home") }) m.Get("/ws", func(ctx *macaron.Context) { conn, err := upgrader.Upgrade(ctx.Resp, ctx.Req.Request, nil) if err != nil { log.Printf("Fail to upgrade connection: %v", err) return } stop := make(chan bool) for { _, data, err := conn.ReadMessage() if err != nil { if err != io.EOF { log.Printf("Fail to read message: %v", err) } return } msg := string(data) switch msg { case "START": if len(people) == 0 { conn.WriteMessage(websocket.TextMessage, []byte("没人了我会乱说?")) conn.Close() return } go sendRandomInfo(conn, stop) case "STOP": stop <- true default: // Find corresponding name to display. for i, p := range people { if p.info == msg { if err = conn.WriteMessage(websocket.TextMessage, []byte(p.name)); err != nil { log.Printf("Fail to send message: %v", err) return } people = append(people[:i], people[i+1:]...) } } } } }) m.Run() }
func TestUnallowedMethods(t *testing.T) { m := macaron.Classic() recorder := httptest.NewRecorder() req, err := http.NewRequest("POST", "/test", strings.NewReader("")) if err != nil { t.Error(err) } m.Any("/test", Messages(), func() int { return http.StatusOK }) m.ServeHTTP(recorder, req) expectStatusCode(t, http.StatusMethodNotAllowed, recorder.Code) }
// When binding from Form data, testing the type of data to bind // and converting a string into that type is tedious, so these tests // cover all those cases. func Test_SetWithProperType(t *testing.T) { Convey("Set with proper type", t, func() { testInputs := map[string]string{ "successful": `integer=-1&integer8=-8&integer16=-16&integer32=-32&integer64=-64&uinteger=1&uinteger8=8&uinteger16=16&uinteger32=32&uinteger64=64&boolean_1=true&fl32_1=32.3232&fl64_1=-64.6464646464&str=string`, "errorful": `integer=&integer8=asdf&integer16=--&integer32=&integer64=dsf&uinteger=&uinteger8=asdf&uinteger16=+&uinteger32= 32 &uinteger64=+%20+&boolean_1=&boolean_2=asdf&fl32_1=asdf&fl32_2=&fl64_1=&fl64_2=asdfstr`, } expectedOutputs := map[string]Everything{ "successful": Everything{ Integer: -1, Integer8: -8, Integer16: -16, Integer32: -32, Integer64: -64, Uinteger: 1, Uinteger8: 8, Uinteger16: 16, Uinteger32: 32, Uinteger64: 64, Boolean_1: true, Fl32_1: 32.3232, Fl64_1: -64.6464646464, Str: "string", }, "errorful": Everything{}, } for key, testCase := range testInputs { httpRecorder := httptest.NewRecorder() m := macaron.Classic() m.Post(testRoute, Form(Everything{}), func(actual Everything, errs Errors) { So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", expectedOutputs[key])) }) req, err := http.NewRequest("POST", testRoute, strings.NewReader(testCase)) if err != nil { panic(err) } req.Header.Set("Content-Type", formContentType) m.ServeHTTP(httpRecorder, req) } }) }
func Test_Render_Extensions(t *testing.T) { Convey("Render with extensions", t, func() { m := macaron.Classic() m.Use(Pongoer(Options{ Directory: "fixtures/basic", Extensions: []string{".tmpl", ".html"}, })) m.Get("/foobar", func(r macaron.Render) { r.HTML(200, "hypertext", map[string]interface{}{}) }) resp := httptest.NewRecorder() req, err := http.NewRequest("GET", "/foobar", nil) So(err, ShouldBeNil) m.ServeHTTP(resp, req) So(resp.Body.String(), ShouldEqual, "Hypertext!") }) }
func Test_Render_Bad_HTML(t *testing.T) { m := macaron.Classic() m.Use(Renderer(Options{ Directory: "fixtures/basic", })) // routing m.Get("/foobar", func(r Render) { r.HTML(200, "nope", nil) }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foobar", nil) m.ServeHTTP(res, req) expect(t, res.Code, 500) expect(t, res.Body.String(), "html/template: \"nope\" is undefined\n") }
func Test_Render_Charset_JSON(t *testing.T) { m := macaron.Classic() m.Use(Renderer(Options{ Charset: "foobar", })) // routing m.Get("/foobar", func(r Render) { r.JSON(300, Greeting{"hello", "world"}) }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foobar", nil) m.ServeHTTP(res, req) expect(t, res.Code, 300) expect(t, res.Header().Get(ContentType), ContentJSON+"; charset=foobar") expect(t, res.Body.String(), `{"one":"hello","two":"world"}`) }
func newMacaronInstance() *macaron.Macaron { m := macaron.Classic() // Middlewares. m.Use(macaron.Renderer(macaron.RenderOptions{ Funcs: []template.FuncMap{funcMap}, })) m.Use(i18n.I18n(i18n.Options{ Langs: setting.Langs, Names: setting.Names, Redirect: true, })) // Routers. m.Get("/", routers.MacaronDocs) m.Get("/docs", routers.MacaronDocs) m.Get("/docs/images/:all", routers.MacaronStatic) m.Get("/docs/*", routers.MacaronDocs) return m }
func main() { m := macaron.Classic() // render html templates from templates directory m.Use(jade.Renderer(jade.Options{ Directory: "templates", // Specify what path to load the templates from. Extensions: []string{".jade"}, // Specify extensions to load for templates. Funcs: []template.FuncMap{map[string]interface{}{ "upper": FuncUpper, }}, // Specify helper function maps for templates to access. Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8". IndentJSON: true, // Output human readable JSON })) m.Get("/", func(r jade.Render) { r.HTML(200, "hello", map[string]string{ "foo": "bar", }) }) m.Run() }
func performMultipartFormTest(t *testing.T, binder handlerFunc, testCase multipartFormTestCase) { httpRecorder := httptest.NewRecorder() m := macaron.Classic() m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { if testCase.shouldSucceed && len(errs) > 0 { So(len(errs), ShouldEqual, 0) } else if !testCase.shouldSucceed && len(errs) == 0 { So(len(errs), ShouldNotEqual, 0) } So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.inputAndExpected)) }) multipartPayload, mpWriter := makeMultipartPayload(testCase) req, err := http.NewRequest("POST", testRoute, multipartPayload) if err != nil { panic(err) } req.Header.Add("Content-Type", mpWriter.FormDataContentType()) err = mpWriter.Close() if err != nil { panic(err) } if testCase.callFormValueBefore { req.FormValue("foo") } m.ServeHTTP(httpRecorder, req) switch httpRecorder.Code { case http.StatusNotFound: panic("Routing is messed up in test fixture (got 404): check methods and paths") case http.StatusInternalServerError: panic("Something bad happened on '" + testCase.description + "'") } }
func Test_Render_HTML(t *testing.T) { m := macaron.Classic() m.Use(Renderer(Options{ Directory: "fixtures/basic", })) // routing m.Get("/foobar", func(r Render) { r.HTML(200, "hello", map[string]string{ "foo": "jeremy", }) }) 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") expect(t, res.Body.String(), "<h1>Hello jeremy</h1>\n") }
func performValidationTest(t *testing.T, testCase validationTestCase) { httpRecorder := httptest.NewRecorder() m := macaron.Classic() m.Post(testRoute, Validate(testCase.data), func(actual Errors) { So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.expectedErrors)) }) req, err := http.NewRequest("POST", testRoute, nil) if err != nil { panic(err) } m.ServeHTTP(httpRecorder, req) switch httpRecorder.Code { case http.StatusNotFound: panic("Routing is messed up in test fixture (got 404): check methods and paths") case http.StatusInternalServerError: panic("Something bad happened on '" + testCase.description + "'") } }
func main() { setting.AppVer = APP_VER log.Info("%s %s", setting.AppName, setting.AppVer) log.Info("Run Mode: %s", strings.Title(macaron.Env)) m := macaron.Classic() m.Use(macaron.Static(setting.ArchivePath, macaron.StaticOptions{ Prefix: "/archive", })) m.Use(pongo2.Pongoer()) m.Use(middleware.Contexter()) m.Get("/", func(ctx *middleware.Context) { ctx.Data["Targets"] = models.Targets ctx.HTML(200, "home") }) if setting.Webhook.Mode == "test" { m.Get("/hook", func(ctx *middleware.Context) { if err := models.Build(ctx.Query("ref")); err != nil { ctx.JSON(500, map[string]interface{}{ "error": err.Error(), }) return } ctx.Status(200) }) } else { m.Post("/hook", func(ctx *middleware.Context) { }) } listenAddr := "0.0.0.0:" + com.ToStr(setting.HTTPPort) log.Info("Listen on http://%s", listenAddr) fmt.Println(http.ListenAndServe(listenAddr, m)) }
func NewApi(adminKey string, metrics met.Backend) *macaron.Macaron { m := macaron.Classic() m.Use(macaron.Renderer()) m.Use(GetContextHandler()) m.Use(Auth(adminKey)) bind := binding.Bind m.Get("/", heartbeat) m.Group("/api/v1", func() { m.Get("/", heartbeat) m.Group("/agents", func() { m.Combo("/"). Get(bind(model.GetAgentsQuery{}), GetAgents). Post(AgentQuota(), bind(model.AgentDTO{}), AddAgent). Put(bind(model.AgentDTO{}), UpdateAgent) m.Get("/:id", GetAgentById) m.Get("/:id/metrics", GetAgentMetrics) m.Delete("/:id", DeleteAgent) }) m.Get("/metrics", bind(model.GetMetricsQuery{}), GetMetrics) m.Group("/tasks", func() { m.Combo("/"). Get(bind(model.GetTasksQuery{}), GetTasks). Post(bind(model.TaskDTO{}), TaskQuota(), AddTask). Put(bind(model.TaskDTO{}), UpdateTask) m.Get("/:id", GetTaskById) m.Delete("/:id", DeleteTask) }) m.Get("/socket/:agent/:ver", socket) }) taskCreate = metrics.NewCount("api.tasks_create") taskDelete = metrics.NewCount("api.tasks_delete") return m }
func main() { m := macaron.Classic() // 服务静态文件 m.Use(macaron.Static("public")) // 在同一个请求中,多个处理器之间可相互传递数据 m.Get("/", handler1, handler2, handler3) // 获取请求参数 m.Get("/q", queryHandler) // 获取远程 IP 地址 m.Get("/ip", ipHandler) // 处理器可以让出处理权限,让之后的处理器先执行 m.Get("/next", next1, next2, next3) // 设置和获取 Cookie m.Get("/cookie/set", setCookie) m.Get("/cookie/get", getCookie) // 响应流 m.Get("/resp", respHandler) // 请求对象 m.Get("/req", reqHandler) // 请求级别容错恢复 m.Get("/panic", panicHandler) // 全局日志器 m.Get("/log", logger) m.Run() }
func newGogsInstance() *macaron.Macaron { m := macaron.Classic() // Middlewares. m.Use(macaron.Renderer(macaron.RenderOptions{ Funcs: []template.FuncMap{funcMap}, })) m.Use(i18n.I18n(i18n.Options{ Langs: setting.Langs, Names: setting.Names, Redirect: true, })) // Routers. m.Get("/", routers.GogsHome) m.Get("/docs", routers.GogsDocs) m.Get("/docs/images/:all", routers.GogsStatic) m.Get("/docs/*", routers.GogsDocs) m.Get("/about", routers.About) m.Get("/team", routers.Team) m.Get("/donate", routers.Donate) return m }