示例#1
0
// Creates new http.Handler that can be used in http.ServeMux (e.g. http.DefaultServeMux)
func NewRouter(baseUrl string, h HandlerFunc, cfg Config) http.Handler {
	router := mux.NewRouter()
	ctx := &context{
		Config:      cfg,
		HandlerFunc: h,
		connections: newConnections(),
	}
	sub := router.PathPrefix(baseUrl).Subrouter()
	sub.HandleFunc("/info", ctx.wrap((*context).infoHandler)).Methods("GET")
	sub.HandleFunc("/info", infoOptionsHandler).Methods("OPTIONS")
	ss := sub.PathPrefix("/{serverid:[^./]+}/{sessionid:[^./]+}").Subrouter()
	ss.HandleFunc("/xhr_streaming", ctx.wrap((*context).XhrStreamingHandler)).Methods("POST")
	ss.HandleFunc("/xhr_send", ctx.wrap((*context).XhrSendHandler)).Methods("POST")
	ss.HandleFunc("/xhr_send", xhrOptions).Methods("OPTIONS")
	ss.HandleFunc("/xhr_streaming", xhrOptions).Methods("OPTIONS")
	ss.HandleFunc("/xhr", ctx.wrap((*context).XhrPollingHandler)).Methods("POST")
	ss.HandleFunc("/xhr", xhrOptions).Methods("OPTIONS")
	ss.HandleFunc("/eventsource", ctx.wrap((*context).EventSourceHandler)).Methods("GET")
	ss.HandleFunc("/jsonp", ctx.wrap((*context).JsonpHandler)).Methods("GET")
	ss.HandleFunc("/jsonp_send", ctx.wrap((*context).JsonpSendHandler)).Methods("POST")
	ss.HandleFunc("/htmlfile", ctx.wrap((*context).HtmlfileHandler)).Methods("GET")
	ss.HandleFunc("/websocket", webSocketPostHandler).Methods("POST")
	ss.HandleFunc("/websocket", ctx.wrap((*context).WebSocketHandler)).Methods("GET")

	sub.HandleFunc("/iframe.html", ctx.wrap((*context).iframeHandler)).Methods("GET")
	sub.HandleFunc("/iframe-.html", ctx.wrap((*context).iframeHandler)).Methods("GET")
	sub.HandleFunc("/iframe-{ver}.html", ctx.wrap((*context).iframeHandler)).Methods("GET")
	sub.HandleFunc("/", welcomeHandler).Methods("GET")
	sub.HandleFunc("/websocket", ctx.wrap((*context).RawWebSocketHandler)).Methods("GET")
	return router
}
示例#2
0
文件: run.go 项目: kisom/hockeypuck
func (c *runCmd) Main() {
	c.configuredCmd.Main()
	InitLog()
	// Create an HTTP request router
	r := mux.NewRouter()
	// Add common static routes
	NewStaticRouter(r)
	// Create HKP router
	hkpRouter := hkp.NewRouter(r)
	// Create SKS peer
	sksPeer, err := openpgp.NewSksPeer(hkpRouter.Service)
	if err != nil {
		die(err)
	}
	// Launch the OpenPGP workers
	for i := 0; i < openpgp.Config().NumWorkers(); i++ {
		w, err := openpgp.NewWorker(hkpRouter.Service, sksPeer)
		if err != nil {
			die(err)
		}
		// Subscribe SKS to worker's key changes
		w.SubKeyChanges(sksPeer.KeyChanges)
		go w.Run()
	}
	sksPeer.Start()
	// Bind the router to the built-in webserver root
	http.Handle("/", r)
	// Start the built-in webserver, run forever
	err = http.ListenAndServe(hkp.Config().HttpBind(), nil)
	die(err)
}
示例#3
0
func main() {
	files, err := filepath.Glob("img/*.jpg")
	if err != nil {
		log.Fatal(err)
		return
	}

	if len(files) == 0 {
		log.Fatal("no images found!")
		return
	}

	sort.Strings(files)

	r := mux.NewRouter()
	h := new(handler)
	h.files = files
	h.start_time = time.Now()

	r.Handle("/{g:[g/]*}{width:[1-9][0-9]*}/{height:[1-9][0-9]*}", h)
	r.Handle("/{g:[g/]*}{width:[1-9][0-9]*}x{height:[1-9][0-9]*}", h)
	r.Handle("/{g:[g/]*}{size:[1-9][0-9]*}", h)
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "public/index.html")
	})

	http.ListenAndServe(":"+os.Getenv("PORT"), r)
}
示例#4
0
文件: env.go 项目: yeison/musicrawler
func New(db *database.Database, directory string) *Environment {
	return &Environment{
		Db:       db,
		Router:   mux.NewRouter(),
		TmplPath: directory,
	}
}
示例#5
0
文件: blog.go 项目: Zensavona/Blog
func main() {
	r := mux.NewRouter()
	http.Handle("/assets/", http.StripPrefix("/assets", http.FileServer(http.Dir("./assets"))))
	r.HandleFunc("/", indexHandler)
	r.HandleFunc(notePath+"{note}", noteHandler)
	http.Handle("/", r)
	http.ListenAndServe(":8080", nil)
}
示例#6
0
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", index)
	r.HandleFunc("/mustache", mustache)
	r.HandleFunc("/tmpl", tmpl)
	http.Handle("/", r)
	http.ListenAndServe(":3000", nil)
}
示例#7
0
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", handler)
	e := http.ListenAndServe(":"+os.Getenv("PORT"), r)
	if e != nil {
		panic(e)
	}
}
示例#8
0
func createmux() *mux.Router {
	r := mux.NewRouter()
	r.HandleFunc("/gull", ListHandler).Methods("GET")
	r.HandleFunc("/gull/{id}", ViewHandler).Methods("GET")
	r.HandleFunc("/gull/{id}", DeleteHandler).Methods("DELETE")
	r.HandleFunc("/gull", AddHandler).Methods("POST")
	return r
}
示例#9
0
func init() {
	r := mux.NewRouter()
	r.HandleFunc("/", HomeHandler)
	r.HandleFunc("/api/kanji/{literal}", KanjiDetailHandler)
	r.HandleFunc("/api/search/{reading}/{term}", KanjiSearchHandler)
	r.HandleFunc("/{path:.*}", HomeHandler)
	http.Handle("/", r)
}
示例#10
0
文件: router.go 项目: nexneo/topturls
func routerSetup() {
	router = mux.NewRouter()
	router.HandleFunc("/", indexHandler)
	router.HandleFunc("/tweet/{id}", showHandler)
	router.HandleFunc("/search", indexHandler)

	http.Handle("/", router)
	http.Handle("/public/", http.FileServer(http.Dir(rootPath)))
}
示例#11
0
func createMux() (r *mux.Router) {
	r = mux.NewRouter()

	r.HandleFunc("/app/observation", ListObservationHandler).Methods("GET")
	r.HandleFunc("/app/observation", AddObservationHandler).Methods("POST")
	r.HandleFunc("/app/observationpoint", ListPointHandler).Methods("GET")
	r.HandleFunc("/app/observationpoint", AddPointHandler).Methods("POST")
	return r
}
示例#12
0
文件: main.go 项目: davecheney/zuul
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/{key}", PageHandler)
	r.HandleFunc("/{key}/{asset}", AssetHandler)
	r.HandleFunc("/static/", http.FileServer(http.Dir(filepath.Join(root, "static"))))
	if err := http.ListenAndServe(":8080", r); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
示例#13
0
func serveBlockpage() {
	r := mux.NewRouter()
	r.PathPrefix("/iframe/").Handler(http.StripPrefix("/iframe", http.FileServer(http.Dir("./blockpage"))))
	r.PathPrefix("/").HandlerFunc(iframeHandler)
	e := http.ListenAndServe(":80", r)
	if e != nil {
		log.Fatalf("serveBlockpage: Could not bind http server: %s", e)
	}
}
示例#14
0
文件: server.go 项目: pleskac/blog
//JSON endpoints:
//	/{ID}		specific post
//	/blog		list of all posts
func endpoint() {
	router := mux.NewRouter()
	r := router.Host("{domain:pleskac.org|www.pleskac.org|localhost}").Subrouter()
	r.HandleFunc("/blog", HomeHandler)
	r.HandleFunc("/blog/{"+postId+":[0-9]+}", PostHandler)
	r.HandleFunc("/{"+postId+":[0-9]+}", PostDataHandler)

	http.ListenAndServe(":1337", r)
}
示例#15
0
func Router() *mux.Router {

	router := mux.NewRouter()

	router.HandleFunc("/", handlers.RenderHtml("main.html"))
	router.HandleFunc("/js/{script:.*}", handlers.RenderJavascripts)

	return router
}
示例#16
0
文件: main.go 项目: jnlopar/shawty
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// read configurations
	confKeys := []string{"SHAWTY_PORT", "SHAWTY_DB", "SHAWTY_DOMAIN", "SHAWTY_MODE", "SHAWTY_LPM", "SHAWTY_LOG_DIR"}
	config := make(map[string]string)
	for _, k := range confKeys {
		config[k] = os.Getenv(k)
	}

	// setup logger
	log.SetDir(config["SHAWTY_LOG_DIR"])

	// setup data
	random := utils.NewBestRand()
	shawties, err := data.NewMySh(random, config["SHAWTY_DB"])
	if err != nil {
		log.Error("Cannot create MySh")
		return
	}
	defer shawties.Close()

	// register routes
	home := web.NewHomeController(config)
	shawtyjs := web.NewShawtyJSController(config, shawties)
	shortID := web.NewShortIDController(config, shawties)

	// setup HTTP server
	router := mux.NewRouter()
	router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
	router.Handle("/", home)
	router.Handle("/shawty.js", shawtyjs)
	router.Handle("/{shortID:[A-Za-z0-9]+}", shortID)

	var port = config["SHAWTY_PORT"]
	if port == "" {
		port = "80"
	}

	l, err := net.Listen("tcp", "0.0.0.0:"+port)
	if err != nil {
		log.Errorf("Cannot listen at %s", port)
		fmt.Println(err)
		return
	}
	defer l.Close()
	log.Infof("Listening at %s", port)

	runMode := config["SHAWTY_MODE"]
	switch runMode {
	case "fcgi":
		fcgi.Serve(l, router)
	default:
		http.Serve(l, router)
	}
}
示例#17
0
// Benchmark_Gorilla runs a benchmark against the Gorilla Mux using
// the default settings.
func Benchmark_GorillaHandler(b *testing.B) {

	handler := gorilla.NewRouter()
	handler.HandleFunc("/person/{last}/{first}", HandlerOk)

	for i := 0; i < b.N; i++ {
		r, _ := http.NewRequest("GET", "/person/anderson/thomas?learn=kungfu", nil)
		w := httptest.NewRecorder()
		handler.ServeHTTP(w, r)
	}
}
示例#18
0
文件: cleo.go 项目: jbowles/gocleo
func InitAndRun(corpusPath, port string) {
	m = &indexContainer{}
	m.iIndex = NewInvertedIndex()
	m.fIndex = NewForwardIndex()

	InitIndex(m.iIndex, m.fIndex, corpusPath)

	r := mux.NewRouter()
	r.HandleFunc("/cleo/{query}", Search)
	http.Handle("/", r)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
示例#19
0
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", HomeHandler)
	r.HandleFunc("/upload", UploadHandler)
	//r.HandleFunc("/{sessionId:[0-9]+}", SessionHandler)
	//r.HandleFunc(`/{sessionId:[0-9]+}/{fileName:.*\.html}`, SessionHandler)
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
	http.Handle("/", r)
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
示例#20
0
文件: mvc.go 项目: WiseBird/trinity
// NewMvcInfrastructure creates a new MvcInfrastructure object
func NewMvcInfrastructure() *MvcInfrastructure {
	mvcI := new(MvcInfrastructure)

	mvcI.handlers = make(map[Controller]map[Action]map[method]*methodDescriptor, 0)
	mvcI.views = make(map[Controller]map[Action]*templateDescriptor, 0)
	//mvcI.controllers = make([]ControllerInterface, 0)
	mvcI.controllerConstructors = make(map[Controller]reflect.Value, 0)

	mvcI.Router = mux.NewRouter()
	mvcI.Router.NotFoundHandler = NewNotFoundHandler(mvcI)

	return mvcI
}
示例#21
0
func init() {
	parseTemplates()

	dec := gomesh.New(template.Must(template.ParseFiles("templates/decorator.html")))

	r := mux.NewRouter()
	r.HandleFunc("/", ensureLogin(home)).Methods("GET")
	r.HandleFunc("/new", ensureLogin(new)).Methods("GET")
	r.HandleFunc("/join", ensureLogin(join)).Methods("POST")
	r.HandleFunc("/{id}", ensureLogin(chat)).Methods("GET")
	r.HandleFunc("/msg/{id}", ensureLogin(msg)).Methods("POST")

	http.Handle("/", dec.Wrap(r))
}
示例#22
0
文件: main.go 项目: hyndio/hyd.me
func main() {
	// http.Dir(".")代表当前路径
	http.Handle("/static/", http.FileServer(http.Dir(".")))
	r := mux.NewRouter()
	for url, handler := range muxHandlers {
		r.HandleFunc(url, handler)
	}
	http.Handle("/", r)
	err := http.ListenAndServe(":8088", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
	log.Print("Start the server.")
}
示例#23
0
文件: main.go 项目: JoonyLi/gopher
func main() {
	http.Handle("/static/", http.FileServer(http.Dir(".")))
	r := mux.NewRouter()
	for url, handler := range handlers {
		r.HandleFunc(url, handler)
	}

	http.Handle("/", r)

	port := config["port"]

	println("Listen", port)
	http.ListenAndServe(":"+port, nil)
}
示例#24
0
func main() {
	kantan_root, _ := os.Getwd()
	if env_kantan_root := os.Getenv("KANTAN_ROOT"); env_kantan_root != "" {
		kantan_root = env_kantan_root
	}
	r := mux.NewRouter()

	ctx := globalContext{kantan_root}

	r.Path("/projects/{project}/repo/git-receive-pack").Handler(&requestHandler{ctx, requestContext.projRepoReceivePackHandler})
	r.PathPrefix("/projects/{project}/repo").Handler(&requestHandler{ctx, requestContext.projRepoHandler})

	http.ListenAndServe(":9090", r)
}
示例#25
0
func router() *mux.Router {
	router := mux.NewRouter()
	router.HandleFunc("/", static).Methods("GET")
	router.HandleFunc("/favicon.ico", static).Methods("GET")
	router.HandleFunc("/site.css", static).Methods("GET")
	entries, err := ioutil.ReadDir("public")
	check(err)
	for _, f := range entries {
		if !strings.Contains(f.Name(), ".") {
			router.HandleFunc("/"+f.Name(), static).Methods("GET")
		}
	}
	router.NotFoundHandler = http.HandlerFunc(notFound)
	return router
}
示例#26
0
func createMux() (r *mux.Router) {
	r = mux.NewRouter()

	r.HandleFunc("/app/games", NewGameHandler).Methods("POST")
	r.HandleFunc("/app/games", ListGamesHandler).Methods("GET")
	r.HandleFunc("/app/games/{name}", ShowGameHandler).Methods("GET")
	r.HandleFunc("/app/games/{name}", DeleteGameHandler).Methods("DELETE")

	r.HandleFunc("/app/games/{name}/scores", CreateScoreHandler).Methods("POST")
	r.HandleFunc("/app/games/{name}/scores", ListScoresHandler).Methods("GET")
	r.HandleFunc("/app/games/{name}/scores/{id:[0-9]+}", ShowScoreHandler).Methods("GET")
	r.HandleFunc("/app/games/{name}/scores/{id:[0-9]+}", DeleteScoreHandler).Methods("DELETE")

	return
}
示例#27
0
文件: web.go 项目: srid/primaupload
func configureRoutes() {
	router := mux.NewRouter()
	router.HandleFunc("/", homeHandler)
	router.HandleFunc("/upload", uploadHandler)
	router.HandleFunc("/view/{filename}", fileInfoHandler)
	router.HandleFunc("/crossdomain.xml", flashCrossDomainFile)

	// static directory handler
	staticDir, err := filepath.Abs("./static")
	if err != nil {
		panic(err)
	}
	staticHandler := http.FileServer(http.Dir(staticDir))
	http.Handle("/static/", http.StripPrefix("/static", staticHandler))
	http.Handle("/", router)
}
示例#28
0
func main() {
	router = mux.NewRouter()

	// Handle /schedule
	router.HandleFunc("/schedule", ListHandler).Methods("GET").Name("Schedule")
	router.HandleFunc("/schedule", CreateHandler).Methods("POST")
	router.HandleFunc("/schedule/{id:[0-9]+}", GetHandler).Methods("GET").Name("Session")
	router.HandleFunc("/schedule/{id:[0-9]+}", UpdateHandler).Methods("PUT")
	router.HandleFunc("/schedule/{id:[0-9]+}", DeleteHandler).Methods("DELETE")

	// Handle resources
	router.PathPrefix("/").Handler(http.FileServer(http.Dir("www")))

	http.Handle("/", router)
	log.Fatal(http.ListenAndServe(":8080", logger(http.DefaultServeMux)))
}
示例#29
0
func main() {
	addr := flag.String("addr", ":8080", "address of the sniffer web interface")
	local := flag.String("local", "localhost:8081", "local address to proxy")
	remote := flag.String("remote", "localhost:8082", "remote address to proxy")

	flag.Parse()

	r := mux.NewRouter()
	r.HandleFunc("/", makeIndex(*local, *remote))
	r.HandleFunc(`/static/{filename:.*\.coffee}.js`, coffeeHandler)
	r.HandleFunc("/static/{filename:.*}", staticHandler)
	r.Handle(`/websocket/`, websocket.Handler(wsockHandler)).Name("wsconn")
	http.Handle("/", r)
	fmt.Printf("Listening on %s\n", *addr)
	log.Fatal(http.ListenAndServe(*addr, nil))
}
示例#30
0
// NewRouter returns a new gosockjs router listening at baseUrl. baseUrl should
// be an absolute path.
func NewRouter(baseUrl string, h Handler) (*Router, error) {
	r := new(Router)

	// Properties
	r.WebsocketEnabled = true
	r.DisconnectDelay = time.Second * 5
	r.HeartbeatDelay = time.Second * 25
	r.handler = h
	r.sessions = make(map[string]*session)

	// Routing
	r.r = mux.NewRouter()
	r.r.StrictSlash(true)
	sub := r.r.PathPrefix(baseUrl).Subrouter()
	sub.StrictSlash(true)
	ss := sub.PathPrefix("/{serverid:[^./]+}/{sessionid:[^./]+}").Subrouter()

	// Greeting, info
	r.r.HandleFunc(baseUrl+"/", r.wrapHandler(greetingHandler)).Methods("GET")
	sub.HandleFunc("/info", infoFunc(r)).Methods("GET", "OPTIONS")

	// Iframe
	sub.HandleFunc("/iframe.html", r.wrapHandler(iframeHandler)).Methods("GET")
	sub.HandleFunc("/iframe-.html", r.wrapHandler(iframeHandler)).Methods("GET")
	sub.HandleFunc("/iframe-{ver}.html", r.wrapHandler(iframeHandler)).Methods("GET")

	// Websockets. We don't worry about sessions.
	sub.HandleFunc("/websocket", r.wrapHandler(rawWebsocketHandler)).Methods("GET")
	ss.HandleFunc("/websocket", r.wrapHandler(websocketHandler))

	// XHR
	ss.HandleFunc("/xhr", r.wrapHandler(xhrHandler)).Methods("POST", "OPTIONS")
	ss.HandleFunc("/xhr_streaming", r.wrapHandler(xhrStreamingHandler)).Methods("POST", "OPTIONS")
	ss.HandleFunc("/xhr_send", r.wrapHandler(xhrSendHandler)).Methods("POST", "OPTIONS")

	// JSONP
	ss.HandleFunc("/jsonp", r.wrapHandler(jsonpHandler)).Methods("GET", "OPTIONS")
	ss.HandleFunc("/jsonp_send", r.wrapHandler(jsonpSendHandler)).Methods("POST", "OPTIONS")

	// Eventsource
	ss.HandleFunc("/eventsource", r.wrapHandler(eventsourceHandler)).Methods("GET", "OPTIONS")

	// HTML
	ss.HandleFunc("/htmlfile", r.wrapHandler(htmlfileHandler)).Methods("GET", "OPTIONS")

	return r, nil
}