Ejemplo n.º 1
0
func mount(war string) {
	log.Println("mount")

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

	m.Get("/", indexHandler)
	m.Get("/events/", sseHandler)
	http.Handle("/", m)

	go func() {
		for i := 0; ; i++ {

			// Create a little message to send to clients,
			// including the current time.
			broker.messages <- fmt.Sprintf(" %d - 哈哈,Oh, Yeah!!! - the time is %v", i, time.Now())

			// Print a nice log message and sleep for 5s.
			log.Printf("Sent message %d ", i)
			time.Sleep(5 * 1e9)

		}
	}()
}
Ejemplo n.º 2
0
func Start() {

	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	// Gitchain API
	r.Post("/rpc", jsonRpcService().ServeHTTP)
	r.Get("/info", info)

	// Git Server
	r.Post("^(?P<path>.*)/git-upload-pack$", func(params martini.Params, req *http.Request) string {
		body, _ := ioutil.ReadAll(req.Body)
		fmt.Println(req, body)
		return params["path"]
	})

	r.Post("^(?P<path>.*)/git-receive-pack$", func(params martini.Params, req *http.Request) string {
		fmt.Println(req)
		return params["path"]
	})

	r.Get("^(?P<path>.*)/info/refs$", func(params martini.Params, req *http.Request) (int, string) {
		body, _ := ioutil.ReadAll(req.Body)
		fmt.Println(req, body)

		return 404, params["path"]
	})

	log.Fatal(http.ListenAndServe(fmt.Sprintf("127.0.0.1:%d", env.Port), m))

}
Ejemplo n.º 3
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))
}
Ejemplo n.º 4
0
func init() {
	m = martini.New()
	//setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(martini.Static("public"))
}
Ejemplo n.º 5
0
/*
Application entry point
*/
func main() {
	m := martini.New()

	//Set middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"OPTIONS", "HEAD", "POST", "GET", "PUT"},
		AllowHeaders:     []string{"Authorization", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	//Create the router
	r := martini.NewRouter()

	//Options matches all and sends okay
	r.Options(".*", func() (int, string) {
		return 200, "ok"
	})

	api.SetupTodoRoutes(r)
	api.SetupCommentRoutes(r)

	mscore.StartServer(m, r)
	fmt.Println("Started NSQ Test service")
}
Ejemplo n.º 6
0
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)
}
Ejemplo n.º 7
0
func launchFrontend() {
	m := martini.New()
	m.Use(martini.Static("static"))
	m.Use(martini.Recovery())
	m.Use(martini.Logger())

	r := martini.NewRouter()
	r.Get("/", indexHandler)
	r.Get("/following", followHandler)
	r.Get("/stat", statHandler)
	r.Get("/channel/:streamer", channelHandler)
	r.Get("/add/:streamer", addHandler)
	r.Get("/del/:streamer", delHandler)
	r.Get("/api/stat/:streamer", apiStat)
	r.Get("/api/channel/:streamer", apiStat)
	r.Get("/api/following", apiFollowing)
	db := getDB()
	redis := getRedis()
	m.Map(db)
	m.Map(redis)

	m.Action(r.Handle)
	log.Print("Started Web Server")
	m.Run()
}
Ejemplo n.º 8
0
func init() {
	m = martini.New()

	//set up middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(auth.Basic(AuthToken, ""))
	m.Use(MapEncoder)

	// set up routes
	r := martini.NewRouter()
	r.Get(`/albums`, GetAlbums)
	r.Get(`/albums/:id`, GetAlbum)
	r.Post(`/albums`, AddAlbum)
	r.Put(`/albums/:id`, UpdateAlbum)
	r.Delete(`/albums/:id`, DeleteAlbum)

	// inject database
	// maps db package variable to the DB interface defined in data.go
	// The syntax for the second parameter may seem weird,
	// it is just converting nil to the pointer-to-DB-interface type,
	// because all the injector needs is the type to map the first parameter to.
	m.MapTo(db, (*DB)(nil))

	// add route action
	// adds the router’s configuration to the list of handlers that Martini will call.
	m.Action(r.Handle)
}
Ejemplo n.º 9
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)
}
Ejemplo n.º 10
0
func init() {
	m = martini.New()

	// I could probably just use martini.Classic() instead of configure these manually

	// Static files
	m.Use(martini.Static(`public`))
	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	// m.Use(auth.Basic(AuthToken, ""))
	m.Use(MapEncoder)

	// Setup routes
	r := martini.NewRouter()
	r.Get(`/albums`, server.GetAlbums)
	r.Get(`/albums/:id`, server.GetAlbum)
	r.Post(`/albums`, server.AddAlbum)
	r.Put(`/albums/:id`, server.UpdateAlbum)
	r.Delete(`/albums/:id`, server.DeleteAlbum)

	// Inject database
	m.MapTo(server.DBInstance, (*server.DB)(nil))
	// Add the router action
	m.Action(r.Handle)
}
Ejemplo n.º 11
0
func withoutLogging() *myClassic {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &myClassic{m, r}
}
Ejemplo n.º 12
0
// NewWebService creates a new web service ready to run.
func NewWebService() *martini.Martini {
	m := martini.New()
	m.Handlers(loggerMiddleware(), martini.Recovery(), gzip.All())
	r := newRouter()
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return m
}
Ejemplo n.º 13
0
func main() {
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Use(martini.Static("public"))
	r := martini.NewRouter()
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	// Instantiate OAuthService with the OAuth App Client Id & Secret from the Environment Variables
	o, err := coinbase.OAuthService(os.Getenv("COINBASE_CLIENT_ID"), os.Getenv("COINBASE_CLIENT_SECRET"), "https://localhost:8443/tokens")
	if err != nil {
		panic(err)
		return
	}

	// At https://localhost:8443/ we will display an "authorize" link
	r.Get("/", func() string {
		authorizeUrl := o.CreateAuthorizeUrl([]string{
			"user",
			"balance",
		})
		link := "<a href='" + authorizeUrl + "'>authorize</a>"
		return link
	})

	// AuthorizeUrl redirects to https://localhost:8443/tokens with 'code' in its
	// query params. If you dont have SSL enabled, replace 'https' with 'http'
	// and reload the page. If successful, the user's balance will show
	r.Get("/tokens", func(res http.ResponseWriter, req *http.Request) string {
		// Get the tokens given the 'code' query param
		tokens, err := o.NewTokensFromRequest(req) // Will use 'code' query param from req
		if err != nil {
			return err.Error()
		}
		// instantiate the OAuthClient
		c := coinbase.OAuthClient(tokens)
		amount, err := c.GetBalance()
		if err != nil {
			return err.Error()
		}
		return strconv.FormatFloat(amount, 'f', 6, 64)
	})

	// HTTP
	go func() {
		if err := http.ListenAndServe(":8080", m); err != nil {
			log.Fatal(err)
		}
	}()

	// HTTPS
	// To generate a development cert and key, run the following from your *nix terminal:
	// go run $(go env GOROOT)/src/pkg/crypto/tls/generate_cert.go --host="localhost"
	if err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", m); err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 14
0
func NewMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &martini.ClassicMartini{Martini: m, Router: r}
}
Ejemplo n.º 15
0
Archivo: web.go Proyecto: h2so5/murcott
func nolog() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Static("public"))
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &martini.ClassicMartini{m, r}
}
Ejemplo n.º 16
0
func newMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &martini.ClassicMartini{m, r}
}
Ejemplo n.º 17
0
func setupServer() *martini.ClassicMartini {
	router := martini.NewRouter()
	server := martini.New()
	server.Use(martini.Recovery())
	server.Use(requestLogger)
	server.MapTo(router, (*martini.Routes)(nil))
	server.Action(router.Handle)
	return &martini.ClassicMartini{server, router}
}
Ejemplo n.º 18
0
func QuietMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	customMartini := martini.New()
	customMartini.Use(customLogger())
	customMartini.Use(martini.Recovery())
	customMartini.Use(martini.Static("public"))
	customMartini.MapTo(r, (*martini.Routes)(nil))
	customMartini.Action(r.Handle)
	return &martini.ClassicMartini{customMartini, r}
}
Ejemplo n.º 19
0
Archivo: web.go Proyecto: CubeLite/gogs
func newMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(middleware.Logger())
	m.Use(martini.Recovery())
	m.Use(martini.Static("public", martini.StaticOptions{SkipLogging: !base.DisableRouterLog}))
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &martini.ClassicMartini{m, r}
}
Ejemplo n.º 20
0
func main() {
	fmt.Println("hello")
	go freeAlloc()
	m := martini.Classic()
	m.Handlers(gzip.All(), martini.Recovery())
	Mount(m, 100)
	log.Printf("start gateway on %s\n", 5050)

	log.Fatal(http.ListenAndServe(":5050", nil))
//	m.RunOnAddr(":5050")
}
Ejemplo n.º 21
0
func testServer() (testServer *martini.ClassicMartini) {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Static("public"))
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	testServer = &martini.ClassicMartini{m, r}
	testServer.Post(server.BuildRoute, webhook.DockerBuild)
	return
}
Ejemplo n.º 22
0
func getMartini() *martini.ClassicMartini {
	//与martini.Classic相比,去掉了martini.Logger() handler  去掉讨厌的http请求日志
	base := martini.New()
	router := martini.NewRouter()
	base.Use(martini.Recovery())
	base.Use(martini.Static("static"))
	base.MapTo(router, (*martini.Routes)(nil))
	base.Action(router.Handle)
	//	return &martini.ClassicMartini{base, router}
	return martini.Classic()
}
Ejemplo n.º 23
0
// getSilentMartini returns a ClassicMartini with logging disabled.
func getSilentMartini() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()
	if *verboseMartini {
		m.Use(martini.Logger())
	}
	m.Use(martini.Recovery())
	m.Use(martini.Static("public"))
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &martini.ClassicMartini{m, r}
}
Ejemplo n.º 24
0
func newClassic() *martini.ClassicMartini {
	r := martini.NewRouter()
	m := martini.New()

	// 日志
	if Conf.Debug {
		m.Use(martini.Logger())
	}

	// 捕获所有错误
	m.Use(martini.Recovery())

	// 静态处理
	m.Use(martini.Static(Conf.StaticDir, Conf.StaticOptions))

	// Session
	store, _ := sessions.NewRediStore(10, "tcp", Conf.RedisAddress, "", []byte(Conf.SessionSecret))
	store.Options(Conf.SessionOptions)
	m.Use(sessions.Sessions(Conf.SessionName, store))

	// csrf
	m.Use(csrf.CsrfInstance.Generate(Conf.CsrfOptions))

	// 缓存中间件
	m.Use(func(c martini.Context, req *http.Request, w http.ResponseWriter) {
		// 覆写ResponseWriter接口
		res := Lib.Http.NewResponseWriter(req, w)
		c.MapTo(res, (*http.ResponseWriter)(nil))

		// Api请求
		if strings.HasPrefix(req.URL.String(), "/api") {
			// 响应类型:Json
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			// GET请求读取缓存
			if !Conf.Debug && req.Method == "GET" {
				// 缓存没过期
				if cache, err := redis.RedisInstance.Get("url-" + req.URL.String()); err == nil {
					w.Write(cache)
					return
				}
			}
		} else {
			// 其他类型请求响应类型:Html
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
		}
	})

	// 返回可以直接调用的路由
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	return &martini.ClassicMartini{m, r}
}
Ejemplo n.º 25
0
func configureServer(server *martini.Martini, router martini.Router) {
	server.Use(martini.Recovery())
	server.Use(middleware.Logger())
	server.Use(martini.Static("templates/public", martini.StaticOptions{SkipLogging: true}))
	server.Use(martini.Static("templates/images", martini.StaticOptions{Prefix: "images", SkipLogging: true}))
	server.Use(martini.Static("templates/styles", martini.StaticOptions{Prefix: "styles", SkipLogging: true}))
	server.Use(martini.Static("templates/scripts", martini.StaticOptions{Prefix: "scripts", SkipLogging: true}))
	server.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))
	server.MapTo(router, (*martini.Routes)(nil))
	server.Action(router.Handle)
}
Ejemplo n.º 26
0
func main() {
	m := martini.New()

	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(render.Renderer())

	r := conf.Router()
	m.MapTo(r, (*martini.Router)(nil))
	m.Action(r.Handle)

	m.Run()
}
Ejemplo n.º 27
0
// Almost equal to martini.Classic(), but this one imports a Logrus logger
func New(logrus *logrus.Logger) *Logrini {
	r := martini.NewRouter()
	m := martini.New()

	m.Map(logrus)

	m.Use(LogriniLogger())
	m.Use(martini.Recovery())
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	return &Logrini{m, r}
}
Ejemplo n.º 28
0
func newTestServer() (testServer *martini.ClassicMartini) {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(martini.Static("public"))
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	testServer = &martini.ClassicMartini{m, r}

	testServer.Post("/docker-build/github", Github)
	testServer.Post("/docker-build/travis", Travis)
	testServer.Post("/docker-build", DockerBuild)
	return
}
Ejemplo n.º 29
0
// custom martini.Classic() for change change martini.Logger() to util.Logger()
func customClassic() *martini.ClassicMartini {
	/*
		- remove martini.Logging()
		- add happo_agent.martini_util.Logging()
	*/
	r := martini.NewRouter()
	m := martini.New()
	m.Use(util.Logger())
	m.Use(martini.Recovery())
	m.Use(martini.Static("public"))
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return &martini.ClassicMartini{m, r}
}
Ejemplo n.º 30
0
func NewApiServer() http.Handler {
	m := martini.New()
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Use(func(w http.ResponseWriter, req *http.Request, c martini.Context) {
		path := req.URL.Path
		if req.Method == "GET" && strings.HasPrefix(path, "/") {
			var remoteAddr = req.RemoteAddr
			var headerAddr string
			for _, key := range []string{"X-Real-IP", "X-Forwarded-For"} {
				if val := req.Header.Get(key); val != "" {
					headerAddr = val
					break
				}
			}
			fmt.Printf("API call %s from %s [%s]\n", path, remoteAddr, headerAddr)
			//if ip := strings.Split(remoteAddr,":");ip[0] != "172.17.140.52" {
			//	w.WriteHeader(404)
			//	return
			//}
		}
		c.Next()
	})
	api := &apiServer{Version: "1.00", Compile: "go"}
	api.Load()
	api.StartDaemonRoutines()
	m.Use(gzip.All())
	m.Use(func(req *http.Request, c martini.Context, w http.ResponseWriter) {
		if req.Method == "GET" && strings.HasPrefix(req.URL.Path, "/teampickwrwithoutjson") {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
		} else {
			w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
			w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
		}
	})
	r := martini.NewRouter()
	r.Get("/", func(r render.Render) {
		r.Redirect("/overview")
	})
	r.Get("/overview", api.showOverview)
	r.Get("/fetch/:account_id", api.fetchId)
	r.Get("/fetchupdate", api.fetchUpdate)
	r.Get("/teampick/:herolist", api.teamPick)
	r.Get("/teampickwr/:herolist", api.teamPickWinRate)
	r.Get("/teampickwrwithoutjson/:herolist", api.teamPickWinRateWithoutJSON)
	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)
	return m
}