Exemplo n.º 1
1
func http() {
	server := martini.Classic()

	server.Use(martini.Static("public", martini.StaticOptions{
		Prefix: "public",
	}))

	server.Use(martini.Static("bower_components", martini.StaticOptions{
		Prefix: "bower_components",
	}))

	server.Use(render.Renderer(render.Options{
		Extensions: []string{".tmpl", ".html"},
		Delims:     render.Delims{"{[{", "}]}"},
	}))

	server.Get("/", func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	//
	server.Get("/clients/:pid", func(params martini.Params, r render.Render) {
		r.HTML(200, "index", params["pid"])
	})

	type jd map[string]interface{}
	type ja []interface{}

	// json api
	server.Get("/api/clients", func(r render.Render) {
		client_info := ja{}

		for _, c := range compositors {
			var surfaces []Surface

			for _, s := range c.Surfaces {
				surfaces = append(surfaces, *s)
			}

			client_info = append(client_info, jd{
				"pid": c.Pid,
				"ss":  surfaces,
			})
		}

		r.JSON(200, client_info)
	})

	// websocket api

	server.Get("/api/clients", websocket.Handler(func(ws *websocket.Conn) {

	}).ServeHTTP)

	server.Get("/api/clients/:pid", websocket.Handler(func(ws *websocket.Conn) {

	}).ServeHTTP)

	server.Run()
}
Exemplo n.º 2
0
func apiv1() {
	url := "/api/v1"
	m.Group(url+"/workplace", func(router martini.Router) {
		router.Post("/auth", binding.Json(controllers.InputWorkplaceAuth{}), controllers.WorkplaceAuth)
		//router.Post("/test", binding.Json(controllers.Test{}), controllers.WorkplacePing)
		//router.Post("/add", binding.Json(controllers.Add{}), controllers.WorkplaceAdd)
		//update
		//delete
		//import

	}, render.Renderer())

	m.Group(url+"/promocode", func(router martini.Router) {

		router.Post("/calc", binding.Json(controllers.InputPromocodeCalc{}), controllers.PromocodeCalc)
		//update
		//delete
		//import

	}, render.Renderer())

	m.Group(url+"/document", func(router martini.Router) {

		router.Post("/add", binding.Json(controllers.InputDocumentAdd{}), controllers.DocumentAdd)
		//update
		//delete
		//import

	}, render.Renderer())

}
Exemplo n.º 3
0
Arquivo: b.go Projeto: supermouseno1/b
// Entry point for running the application.
// It defines all routes and middleware used
// and starts the underlying server.
func Start() {
	// Set up our Martini instance
	m := martini.Classic()

	// Middleware
	// m.Use(gzip.All())
	m.Use(render.Renderer())

	// Routes
	m.Group("/admin", func(r martini.Router) {
		a := handlers.Admin{}

		r.Get("", a.Index)
		r.Get("/posts", a.Posts.Index)
		r.Get("/posts/new", a.Posts.New)
		r.Get("/posts/:id/edit", a.Posts.Edit)

	}, render.Renderer(render.Options{
		Layout: "admin/layout",
	}))

	m.Group("/api", func(r martini.Router) {
		a := handlers.Api{}

		r.Get("", a.Index)
		r.Get("/posts", a.Posts.Index)
		r.Post("/posts", a.Posts.Create)
		r.Get("/posts/:id", a.Posts.Show)
		r.Get("/render/markdown", a.Render.Markdown)
	})

	// Serve from static if possible
	m.Use(martini.Static(util.Config().App.SiteDir))
	m.Run()
}
Exemplo n.º 4
0
func (this *Server) Run(withRandomPort ...bool) {
	this.Martini.Use(cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"PUT", "PATCH", "DELETE", "GET", "OPTIONS", "POST"},
		AllowCredentials: true,
	}))
	this.Martini.Use(render.Renderer())

	this.Martini.Group("/eureka", func(r martini.Router) {
		for _, request := range this.getRequestsEureka() {
			request.SetRoutes(r)
		}
	})
	this.registerJobsRoutes()
	if len(withRandomPort) > 0 && withRandomPort[0] {
		listener, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			loggerServer.Severe("Error when getting a free random port: %v", err.Error())
		}
		host := listener.Addr().String()
		listener.Close()
		this.Martini.RunOnAddr(host)
	} else if config.GetConfig().Host != "" {
		this.Martini.RunOnAddr(config.GetConfig().Host)
	} else {
		this.Martini.Run()
	}

}
Exemplo n.º 5
0
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)
}
Exemplo n.º 6
0
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()
}
Exemplo n.º 7
0
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)
}
Exemplo n.º 8
0
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
}
Exemplo n.º 9
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(martini.Logger())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	store := sessions.NewCookieStore([]byte(CookieSecret))
	m.Use(sessions.Sessions("bunkaisession", store))
	log.Println("env is", martini.Env)
	m.Map(martini.Env)

	m.Group("/", func(m martini.Router) {
		m.Get("", Home)
	}, AssetMap)

	m.Group("/api", func(m martini.Router) {
		m.Post("/login", PostLogin)
		m.Post("/users", UserCreate)

		m.Group("/sentences", func(m martini.Router) {
			m.Post("", SentenceCreate)
			m.Get("", SentenceList)
			m.Delete("/:id", SentenceDelete)
		}, RequireLogin)

		m.Group("/users", func(m martini.Router) {
			m.Post("/logout", Logout)
			m.Get("/me", UserGet)
		}, RequireLogin)
	})

	m.Run()
}
Exemplo n.º 10
0
func App() *martini.ClassicMartini {
	m := martini.Classic()

	m.Use(gzip.All())

	m.Use(render.Renderer(render.Options{
		Directory: "templates",
	}))

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	m.Get("", Index)

	m.Group("/repos", func(r martini.Router) {
		r.Get("", ReposIndex)
		r.Get("/:name", ReposShow)
	})

	m.Group("/orgs", func(r martini.Router) {
		r.Get("", OrgsIndex)
		r.Get("/:id", OrgsShow)
	})

	m.Group("/users", func(r martini.Router) {
		r.Get("", UserIndex)
		r.Get("/:id", UserShow)
	})

	m.Get("/stats", StatsIndex)
	m.Get("/issues", IssuesIndex)

	return m
}
Exemplo n.º 11
0
Arquivo: main.go Projeto: xuender/pen
func main() {
	log.Info("启动")
	//读取配置文件
	base.BaseConfig.Read("config.json")
	// 初始化数据库
	base.InitDb()
	// 检查文件完整性
	//err := base.CheckFiles()
	//if(err!=nil){
	//  log.Error(err)
	//  return
	//}
	m := martini.Classic()
	// gzip支持
	m.Use(gzip.All())
	// 模板支持
	m.Use(render.Renderer())
	//
	m.Get("/meta.js", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/javascript")
		w.Write([]byte(base.GetMetaJs()))
	})
	// websocket 支持
	m.Get("/ws", websocket.Handler(base.WsHandler).ServeHTTP)
	m.NotFound(func(r render.Render) {
		r.HTML(404, "404", nil)
	})
	log.Info(fmt.Sprintf("访问地址 http://localhost:%d", base.BaseConfig.Web.Port))
	// 端口号
	http.ListenAndServe(fmt.Sprintf(":%d", base.BaseConfig.Web.Port), m)
	// m.Run()
	log.Info("退出")
}
Exemplo n.º 12
0
func main() {
	m := martini.Classic()

	store := sessions.NewCookieStore([]byte("secret-isucon"))
	m.Use(sessions.Sessions("isucon_go_session", store))

	m.Use(martini.Static("../public"))
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Get("/", func(r render.Render, session sessions.Session) {
		r.HTML(200, "index", map[string]string{"Flash": getFlash(session, "notice")})
	})

	m.Post("/login", func(req *http.Request, r render.Render, session sessions.Session) {
		user, err := attemptLogin(req)

		notice := ""
		if err != nil || user == nil {
			switch err {
			case ErrBannedIP:
				notice = "You're banned."
			case ErrLockedUser:
				notice = "This account is locked."
			default:
				notice = "Wrong username or password"
			}

			session.Set("notice", notice)
			r.Redirect("/")
			return
		}

		session.Set("user_id", strconv.Itoa(user.ID))
		r.Redirect("/mypage")
	})

	m.Get("/mypage", func(r render.Render, session sessions.Session) {
		currentUser := getCurrentUser(session.Get("user_id"))

		if currentUser == nil {
			session.Set("notice", "You must be logged in")
			r.Redirect("/")
			return
		}

		currentUser.getLastLogin()
		r.HTML(200, "mypage", currentUser)
	})

	m.Get("/report", func(r render.Render) {
		r.JSON(200, map[string][]string{
			"banned_ips":   bannedIPs(),
			"locked_users": lockedUsers(),
		})
	})

	http.ListenAndServe(":8080", m)
}
Exemplo n.º 13
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Get("/", func(ren render.Render, r *http.Request, db *sql.DB) {
		searchTerm := "%" + r.URL.Query().Get("search") + "%"
		rows, err := db.Query(`SELECT title, author, description FROM books
                           WHERE title ILIKE $1
                           OR author ILIKE $1
                           OR description ILIKE $1`, searchTerm)
		PanicIf(err)
		defer rows.Close()

		books := []Book{}
		for rows.Next() {
			book := Book{}
			err := rows.Scan(&book.Title, &book.Author, &book.Description)
			PanicIf(err)
			books = append(books, book)
		}

		ren.HTML(200, "books", books)
	})

	m.Run()
}
Exemplo n.º 14
0
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()
}
Exemplo n.º 15
0
func main() {
	m := martini.Classic()

	//middleware
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Get("/", func(r render.Render) {
		r.HTML(200, "index", "")
	})

	m.Get("/new", func(r render.Render) {
		var v map[string]interface{}

		values := url.Values{}
		res, err := http.PostForm("http://requestb.in/api/v1/bins", values)

		if err != nil {
			r.JSON(500, map[string]interface{}{"error": err})
		} else {
			defer res.Body.Close()

			err = json.NewDecoder(res.Body).Decode(&v)

			if err != nil {
				r.JSON(500, map[string]interface{}{"error": err})
			}
		}

		r.HTML(200, "new", v)
	})

	m.Run()
}
Exemplo n.º 16
0
func main() {
	m := martini.Classic()

	m.Use(gzip.All())

	// render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Use(DB())

	m.Get("/", func(r render.Render, db *mgo.Database) {
		data := map[string]interface{}{"quotes": GetAll(db)}
		r.HTML(200, "list", data)
	})

	m.Post("/", binding.Form(Quote{}), func(r render.Render, db *mgo.Database, quote Quote) {
		db.C("quotes").Insert(quote)
		data := map[string]interface{}{"quotes": GetAll(db)}
		r.HTML(200, "list", data)
	})

	m.Run()
}
Exemplo n.º 17
0
func main() {
	// init server
	err := server.Init("httpaccess")
	if err != nil {
		server.Log.Fatal(err)
		return
	}

	// martini setup
	martini.Env = martini.Prod
	handler := martini.Classic()
	handler.Use(render.Renderer())
	route(handler)

	// register a http handler
	err = server.RegisterHTTPHandler(handler)
	if err != nil {
		server.Log.Errorf("RegisterHTTPHandler Error: %s", err)
		return
	}

	// go
	err = server.Run()
	if err != nil {
		server.Log.Fatal(err)
	}
}
Exemplo n.º 18
0
//InitSession - initializes authentication middleware for controllers
func InitSession(m *martini.ClassicMartini, rc redisCreds) {
	m.Use(render.Renderer())

	if rediStore, err := sessions.NewRediStore(10, "tcp", rc.Uri(), rc.Pass(), []byte(sessionSecret)); err == nil {
		m.Use(sessions.Sessions(sessionName, rediStore))
	}
}
Exemplo n.º 19
0
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()

}
Exemplo n.º 20
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
		Funcs: []template.FuncMap{
			{
				"unescaped": func(args ...interface{}) template.HTML {
					return template.HTML(args[0].(string))
				},
			},
		},
	}))

	//Sessions
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("vsauth", store))

	m.Get("/", IndexArticles)
	m.Get("/create", CreateArticle)
	m.Get("/read", ReadArticle)
	m.Get("/update", UpdateArticle)
	m.Get("/delete", DeleteArticle)
	m.Post("/save", SaveArticle)
	m.Get("/login", LoginForm)
	m.Post("/login", UserLogin)
	m.Get("/signup", SignupForm)
	m.Post("/signup", UserSignup)
	m.Get("/logout", UserLogout)
	m.Get("/wrong", WrongLogin)

	m.Run()
}
Exemplo n.º 21
0
func Mount(m *martini.ClassicMartini, concurrent int) {


	fmt.Println("concurrent @v:", concurrent)
	m.Use(utee.MidConcurrent(concurrent))
	m.Use(render.Renderer())
	m.Use(utee.MidTextDefault)
	//	//map request web utilities
	m.Use(func(w http.ResponseWriter, c martini.Context) {
		web := &utee.Web{W: w}
		c.Map(web)
	})
	m.Use(func(c martini.Context){
		var msgs []string
		for i:=0;i<100000;i++ {
			msgs = append(msgs,fmt.Sprint("testMsg",i))
		}
		c.Map(msgs)
	})

	m.Group("/hello", func(r martini.Router) {
		r.Post("/world", test)
		r.Get("/world", test)
	})
	http.Handle("/", m)
//	http.HandleFunc("/test/a", testhandler)
}
func main() {
	res, _ := filepath.Glob("templates\\temp\\*.html")
	log.Printf("%+v", res)
	var templates = template.Must(template.ParseGlob("templates\\temp\\*.html"))
	err := templates.ExecuteTemplate(
		os.Stdout,
		"indexPage",
		View{Content: "foo"},
	)
	if err != nil {
		log.Printf("err: %v", err)
		return
	}

	m := martini.Classic()
	// render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Directory:  "templates/temp",
		Extensions: []string{".html"},
	}))

	m.Get("/", func(r render.Render) {
		r.HTML(200, "head", View{Content: "tututrutu"}, render.HTMLOptions{Layout: "indexPage"})
	})

	m.Run()
}
Exemplo n.º 23
0
func main() {
	username, password := waitForPostgres(serviceName)
	db, err := postgres.Open(serviceName, fmt.Sprintf("dbname=postgres user=%s password=%s", username, password))
	if err != nil {
		log.Fatal(err)
	}

	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Action(r.Handle)
	m.Map(db)

	r.Post("/databases", createDatabase)
	r.Get("/ping", ping)

	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	addr := ":" + port

	if err := discoverd.Register(serviceName+"-api", addr); err != nil {
		log.Fatal(err)
	}

	log.Fatal(http.ListenAndServe(addr, m))
}
Exemplo n.º 24
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Charset:   "utf-8",
	}))

	m.NotFound(func(r render.Render) {
		r.Redirect("/")
	})

	m.Get("/", IndexRender)

	m.Get("/feed", FeedRender)

	m.Get("/hello", func(r render.Render) {
		//r.HTML(200, "hello", "World")
		r.HTML(200, Greet("Golang"), "World")
	})

	m.Get("/api", func(r render.Render) {
		r.JSON(200, map[string]interface{}{"hello": "world"})
	})

	m.Run()
}
Exemplo n.º 25
0
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()
}
Exemplo n.º 26
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))
	m.Use(martini.Static("assets"))

	m.Get("/", func(ren render.Render, r *http.Request, db *sql.DB) {
		rows, err := db.Query("SELECT * from videos")
		PanicIf(err)
		defer rows.Close()

		videos := []Video{}
		for rows.Next() {
			v := Video{}
			err := rows.Scan(&v.Id, &v.Title)
			PanicIf(err)
			videos = append(videos, v)
			// fmt.Fprintf(rw, "Title: %s", title)
		}

		ren.HTML(200, "videos", videos)
	})

	m.Run()
}
Exemplo n.º 27
0
//初始化并启动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)
	}
} // }}}
Exemplo n.º 28
0
func Start() {
	fmt.Println("Starting Liliput..")
	syslog.Openlog("lilliput", syslog.LOG_PID, syslog.LOG_USER)

	m := martini.Classic()
	// render home page
	m.Use(render.Renderer(render.Options{
		Directory:  "static",
		Extensions: []string{".html"},
		Charset:    "UTF-8",
	}))

	gorelic.InitNewrelicAgent(Get("newrelic.license", "").(string), Get("lilliput.domain", "").(string), true)
	m.Use(gorelic.Handler)

	m.Get("/:token", Redirect)
	m.Get("/", func(r render.Render) {
		r.HTML(200, "index", nil)
	})
	m.Post("/", TinyUrl)
	server := fmt.Sprintf("%s:%s",
		Get("redis.server", ""),
		Get("redis.port", ""))
	m.Map(NewPool(server))

	port := fmt.Sprintf(":%v", Get("lilliput.port", ""))
	fmt.Println("Started on " + port + "...")
	http.Handle("/", m)
	http.ListenAndServe(port, nil)
	m.Run()
}
Exemplo n.º 29
0
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
}
Exemplo n.º 30
0
/*
 * Main function
 */
func main() {
	m := martini.Classic()

	//sessions
	store := sessions.NewCookieStore([]byte("yyt726ddd318"))
	m.Use(sessions.Sessions("yunyun", store))

	m.Map(GetMongoDB())
	m.Map(GetKotobaCollection())
	//render html templates from directory
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Post(auth.FUNC_LOGIN, auth.PostLogin)
	m.Post(auth.FUNC_REGISTER, auth.Register)
	m.Get(auth.FUNC_LOGOUT, auth.Logout)
	m.Post(FUNC_SEARCH, auth.RequireLogin, kotoba.Search)
	m.Get(FUNC_HOME, auth.RequireLogin, kotoba.Home)
	m.Get(PAGE_ADD, auth.RequireLogin, AddWord)
	m.Get(FUNC_KOTOBA, auth.RequireLogin, kotoba.ShowKotoba)
	m.Post(FUNC_ADD, auth.RequireLogin, kotoba.AddKotoba)
	m.Get(PAGE_REVIEW, auth.RequireLogin, kotoba.DoReviews)
	m.Post(FUNC_CHECK, auth.RequireLogin, kotoba.CheckReview)
	m.Get(PAGE_EDIT, auth.RequireLogin, kotoba.EditKotoba)
	m.Post(FUNC_EDIT, auth.RequireLogin, kotoba.SaveEditKotoba)
	m.Get(PAGE_STATS, auth.RequireLogin, kotoba.ShowStats)
	// todo: not yet implemented
	//m.Get(apiReviews, auth.RequireLogin, GetReviews)

	m.Run()
}