Example #1
0
func main() {

	err := LoadConfig()
	if err != nil {
		log.Fatal("Could not load config file hidemyemail.cfg")
		return
	}

	g_conn_string = g_config.DbConnectionString

	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(g_config.ResourcePath+"/images"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir(g_config.ResourcePath+"/css"))))
	http.HandleFunc("/add",
		func(w http.ResponseWriter, r *http.Request) {
			handleAdd(w, r)
		})
	http.HandleFunc("/get",
		func(w http.ResponseWriter, r *http.Request) {
			handleGet(w, r)
		})
	http.HandleFunc("/",
		func(w http.ResponseWriter, r *http.Request) {
			handleGetCaptcha(w, r)
		})
	log.Fatal(http.ListenAndServe(":"+g_config.Port, nil))
}
Example #2
0
func main() {
	defer db.Close()
	http.HandleFunc("/main", handleMain)
	http.HandleFunc("/demo", handleDemo)
	http.HandleFunc("/logout", auth.HandleLogout)
	http.HandleFunc("/authorize", auth.HandleAuthorize)
	http.HandleFunc("/oauth2callback", auth.HandleOAuth2Callback)
	http.HandleFunc("/categoryList/", handleCategoryList)
	http.HandleFunc("/category/", handleCategory)
	http.HandleFunc("/feed/list/", handleFeedList)
	http.HandleFunc("/feed/new/", handleNewFeed)
	http.HandleFunc("/feed/", handleFeed)
	http.HandleFunc("/entry/mark/", handleMarkEntry)
	http.HandleFunc("/entry/", handleEntry)
	http.HandleFunc("/entries/", handleEntries)
	http.HandleFunc("/menu/select/", handleSelectMenu)
	http.HandleFunc("/menu/", handleMenu)
	http.HandleFunc("/stats/", handleStats)
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
	http.Handle("/favicon.ico", http.StripPrefix("/favicon.ico", http.FileServer(http.Dir("./static/favicon.ico"))))
	http.HandleFunc("/", handleRoot)

	go feed.CacheAllCats()  //create cache for categories at startup
	go feed.CacheAllFeeds() //create cache for feeds at startup
	print("Listening on 127.0.0.1:" + port + "\n")
	http.ListenAndServe("127.0.0.1:"+port, nil)
}
Example #3
0
func init() {
	initTemplate()
	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/find/", findHandler)
	http.Handle("/css/", http.FileServer(http.Dir(".")))
	http.Handle("/js/", http.FileServer(http.Dir(".")))
}
Example #4
0
func main() {

	var err error

	cwd, _ := os.Getwd()
	client := flag.String("client", path.Join(cwd, "client"), "Full path to client directory.")
	addr := flag.String("listen", "127.0.0.1:8088", "Listen address.")

	templates, err = template.ParseGlob(path.Join(*client, "*.html"))
	if err != nil {
		log.Fatal("Failed to load templates: ", err)
	}

	flag.Parse()
	go h.run()
	http.HandleFunc("/", serveClient)
	http.HandleFunc("/realtimetraffic", serveWs)
	http.Handle("/css/", http.FileServer(http.Dir(*client)))
	http.Handle("/scripts/", http.FileServer(http.Dir(*client)))
	http.Handle("/img/", http.FileServer(http.Dir(*client)))
	http.Handle("/favicon.ico", http.FileServer(http.Dir(*client)))

	err = http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}

}
Example #5
0
func Serve(httpAddress *string, db core.Database, s *search.Searcher, devAssets bool, updater *torrent.StatsUpdater) {

	// Add SVG to mime directory
	mime.AddExtensionType(".svg", "image/svg+xml")

	r := mux.NewRouter()

	apirouter := ApiRouter(db, s, updater)

	r.PathPrefix("/api/").Handler(apirouter)
	if devAssets {
		log.Println("Debug mode is on. Serving development assets from angular/app.")
		r.PathPrefix("/styles/").Handler(http.FileServer(http.Dir("frontend/angular/.tmp/")))
		r.PathPrefix("/bower_components/").Handler(http.FileServer(http.Dir("frontend/angular/")))
		r.PathPrefix("/").Handler(NotFoundHook{
			http.FileServer(http.Dir("frontend/angular/app/")),
			"frontend/angular/app/index.html"})
	} else {
		r.PathPrefix("/").Handler(NotFoundHook{
			http.FileServer(http.Dir("frontend/angular/dist/")),
			"frontend/angular/dist/index.html"})
	}
	http.Handle("/", r)
	log.Println("Web server listening on", *httpAddress)
	err := http.ListenAndServe(*httpAddress, nil)
	if err != nil {
		log.Println(err)
	}
}
Example #6
0
func (this *HttpEndpoint) registerStaticHandlers(staticPath string) {
	this.mux.Handle("/", http.FileServer(http.Dir(staticPath)))
	pathPrefix := "/tutorial/"
	pathValue := staticPath + pathPrefix
	this.mux.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
		http.FileServer(http.Dir(pathValue))))
}
Example #7
0
func main() {
	flag.Parse()

	if *index != "" {
		searcher = search.NewSearcher(*index, *prefix)
	}

	r := mux.NewRouter()

	r.PathPrefix("/src").Methods("GET").
		Handler(http.StripPrefix("/src", http.FileServer(http.Dir(*src))))

	r.PathPrefix("/api/search").Methods("POST").HandlerFunc(searchHandler)

	// Single-page app URLs are always served with the index page.
	r.PathPrefix("/file/").Methods("GET").
		Handler(&SingleFile{path.Join(*app, "index.html")})
	r.Path("/search").Methods("GET").
		Handler(&SingleFile{path.Join(*app, "index.html")})

	r.PathPrefix("/").Methods("GET").
		Handler(http.FileServer(http.Dir(*app)))

	http.ListenAndServe(":8080", r)
}
Example #8
0
func init() {
	if templates == nil {
		templates = make(map[string]*template.Template)
	}
	templates["index"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/index.tmpl"))
	templates["index1"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/index1.tmpl"))
	templates["edit"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/edit.tmpl"))
	templates["preview"] = template.Must(template.ParseFiles("tmpl/preview.tmpl"))

	//handle image/css and generated html files
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
	http.Handle("/_images/", http.StripPrefix("/_images/", http.FileServer(http.Dir("_images"))))
	http.Handle("/_html/", http.StripPrefix("/_html/", http.FileServer(http.Dir("_html"))))
	http.Handle("/_html/_images/", http.StripPrefix("/_html/_images/", http.FileServer(http.Dir("_html/_images"))))
	http.Handle("/_html/css", http.StripPrefix("/_html/css", http.FileServer(http.Dir("_html/css"))))

	// set up html options
	htmlExt = 0
	htmlExt |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
	htmlExt |= blackfriday.EXTENSION_TABLES
	htmlExt |= blackfriday.EXTENSION_FENCED_CODE
	htmlExt |= blackfriday.EXTENSION_AUTOLINK
	htmlExt |= blackfriday.EXTENSION_STRIKETHROUGH
	htmlExt |= blackfriday.EXTENSION_SPACE_HEADERS

	htmlFlags = blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_USE_SMARTYPANTS |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES |
		blackfriday.HTML_FOOTNOTE_RETURN_LINKS |
		blackfriday.HTML_SMARTYPANTS_ANGLED_QUOTES

}
Example #9
0
func main() {
	parseConstants()
	PrefixLookup.LoadPrefixes()

	file, e := ioutil.ReadFile(qsoFile)
	if e != nil {
		fmt.Printf("File error: %v\n", e)
		os.Exit(1)
	}

	json.Unmarshal(file, &qsls)

	listOfContactedCountries = getListOfCountries()
	listOfContactsPerCountry = getContactsPerCountry()
	http.Handle("/compressedCards/", http.StripPrefix("/compressedCards",
		http.FileServer(http.Dir(path.Join(rootdir, convertedFolder)))))
	http.Handle("/thumbnails/", http.StripPrefix("/thumbnails",
		http.FileServer(http.Dir(path.Join(rootdir, resizedFolder)))))
	http.Handle("/cards/", http.StripPrefix("/cards",
		http.FileServer(http.Dir(path.Join(rootdir, cardsFolder)))))
	http.Handle("/images/", http.StripPrefix("/images",
		http.FileServer(http.Dir(path.Join(rootdir, imagesFolder)))))
	http.Handle("/html/", http.StripPrefix("/html",
		http.FileServer(http.Dir(path.Join(rootdir, "/html")))))

	http.HandleFunc("/", index)
	http.HandleFunc("/browse/", browse)
	http.HandleFunc("/country/", browseCountry)
	http.HandleFunc("/view/", displayCard)
	http.HandleFunc("/api/", apiGetCall)

	fmt.Printf("Web Server started\n")
	http.ListenAndServe(":8080", nil)
}
Example #10
0
func main() {
	flagWork := flag.String("work", "work", "")
	flagAddr := flag.String("addr", ":4020", "")
	flag.Parse()

	root, err := rootPath()
	if err != nil {
		panic(err)
	}

	r := pork.NewRouter(
		func(status int, r *http.Request) {
			log.Printf("%d - %s", status, r.URL.Path)
		}, nil, nil)

	r.RespondWith("/", pork.Content(pork.NewConfig(pork.None),
		http.Dir(filepath.Join(root, "src/pub"))))
	r.RespondWith("/data/", pork.Content(pork.NewConfig(pork.None),
		http.Dir(*flagWork)))

	log.Printf("Server running on address %s\n", *flagAddr)
	if err := http.ListenAndServe(*flagAddr, r); err != nil {
		panic(err)
	}
}
Example #11
0
func (server *WebServer) listen() {
	if server.httpServer.FileDescriptor == 0 {
		server.LogInfoF("listening on %s", server.httpServer.Addr)
	} else {
		server.LogInfoF("listening on existing file descriptor %d, %s", server.httpServer.FileDescriptor, server.httpServer.Addr)
	}

	handleFunc("/", server.logReq, server.index)
	//handleFunc("/restart", server.logReq, server.restart)
	//handleFunc("/shutdown", server.logReq, server.shutdown)
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./app/css"))))
	http.Handle("/imgs/", http.StripPrefix("/imgs/", http.FileServer(http.Dir("./app/imgs"))))
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./app/js"))))
	items := []string{"apple-touch-icon.png", "crossdomain.xml", "favicon.ico", "humans.txt", "robots.txt", "tile-wide.png", "tile.png", "browserconfig.xml"}
	for _, k := range items {
		handleFunc("/"+k, server.logReq, func(w http.ResponseWriter, req *http.Request) {
			http.ServeFile(w, req, "./"+k)
		})
	}

	err := server.httpServer.ListenAndServe()
	if err != nil {
		server.LogErr(err)
		server.Close()
	}
}
Example #12
0
File: main.go Project: nesv/uhttpd
func main() {
	flag.Parse()
	log.SetPrefix(*LogPrefix + " ")
	if *DocumentRoot == "" {
		log.Fatalln("You must specify a directory to serve, with '-dir=\"...\"'")
	}

	handler := http.FileServer(http.Dir(*DocumentRoot))
	if *Logging {
		// Set the logger output.
		var output io.Writer
		if *LogPath == "" {
			output = os.Stdout
		} else {
			var err error
			flags := os.O_CREATE | os.O_APPEND | os.O_WRONLY
			output, err = os.OpenFile(*LogPath, flags, 0644)
			if err != nil {
				log.Fatal(err.Error())
			}
		}
		handler = LoggingHandler(output, http.FileServer(http.Dir(*DocumentRoot)))
		log.Printf("Serving %q", *DocumentRoot)
		log.Printf("Listening on %q", *ListenAddr)
	}
	if err := http.ListenAndServe(*ListenAddr, handler); err != nil {
		log.Fatalln(err)
	}

	return
}
Example #13
0
func main() {
	//Have to add handles for serving static pages, still a bit fuzzy on the FileServer stuff.
	http.Handle("/pic/", http.StripPrefix("/pic/", http.FileServer(http.Dir("pic"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
	http.HandleFunc("/", handleThis)
	http.ListenAndServe(":8000", nil)
}
Example #14
0
func main() {
	client = redis.NewClient(&redis.Options{
		Addr:     RedisAddr,
		Password: RedisPassword,
		DB:       RedisDb,
	})
	pong, err := client.Ping().Result()

	http.Handle("/css/", http.FileServer(http.Dir("template")))
	http.Handle("/js/", http.FileServer(http.Dir("template")))
	http.Handle("/img/", http.FileServer(http.Dir("template")))
	http.Handle("/", http.FileServer(http.Dir("template")))

	if err != nil {
		fmt.Println(pong, err)
		http.HandleFunc("/set", showerror)
		http.HandleFunc("/get", showerror)
		http.HandleFunc("/tag", showerror)
	} else {
		http.HandleFunc("/set", sethello)
		http.HandleFunc("/get", gethello)
		http.HandleFunc("/tag", taghello)
	}
	http.ListenAndServe(":"+Port, nil)
}
Example #15
0
func init() {
	r := mux.NewRouter()

	apiGet := r.PathPrefix("/api").Methods("GET").Subrouter()
	apiGet.HandleFunc("/{view}", apiController.ApiGetHandler)
	apiGet.HandleFunc("/{view}/{key}", apiController.ApiGetHandler)
	apiGet.HandleFunc("/{view}/{parent}/{key}", apiController.ApiGetHandler)

	apiPost := r.PathPrefix("/api").Methods("POST").Subrouter()
	apiPost.HandleFunc("/{view}", apiController.ApiPostHandler)
	apiPost.HandleFunc("/{view}/{key}", apiController.ApiPostHandler)

	apiDelete := r.PathPrefix("/api").Methods("DELETE").Subrouter()
	apiDelete.HandleFunc("/{view}/{key}", apiController.ApiDeleteHandler)

	r.PathPrefix("/admin/").Handler(http.StripPrefix("/admin/", http.FileServer(http.Dir("./static/admin"))))
	r.PathPrefix("/admin").Handler(http.RedirectHandler("/admin/", 301))

	r.PathPrefix("/blog").Handler(http.StripPrefix("/blog", http.FileServer(http.Dir("./static"))))

	r.PathPrefix("/foundation/").Handler(http.StripPrefix("/foundation/", http.FileServer(http.Dir("./static/foundation"))))

	r.HandleFunc("/{.path:.*}", cloudAdminHandler).Methods("GET")
	r.HandleFunc("/{.path:.*}", cloudAdminPostHandler).Methods("POST")

	http.Handle("/", r)
}
Example #16
0
func main() {
	// filename := flag.String("config", "config.toml", "Path to configuration file")
	//
	// flag.Parse()
	filename := "config.toml"
	defer glog.Flush()

	var application = &system.Application{}

	application.Init(&filename)
	application.LoadTemplates()

	// Setup static files
	static := web.New()
	publicPath := application.Config.Get("general.public_path").(string)
	static.Get("/assets/*", http.StripPrefix("/assets/", http.FileServer(http.Dir(publicPath))))

	http.Handle("/assets/", static)

	// Apply middleware
	//goji.Use(application.ApplyTemplates)
	//goji.Use(application.ApplySessions)
	//goji.Use(application.ApplyDbMap)
	goji.Use(application.ApplyGormDB)
	//goji.Use(application.ApplyAuth)
	//goji.Use(application.ApplyIsXhr)
	//goji.Use(application.ApplyCsrfProtection)
	//goji.Use(context.ClearHandler)

	controller := &controllers.MainController{}

	// Couple of files - in the real world you would use nginx to serve them.
	goji.Get("/robots.txt", http.FileServer(http.Dir(publicPath)))
	goji.Get("/favicon.ico", http.FileServer(http.Dir(publicPath+"/images")))

	// Home page
	goji.Get("/", application.Route(controller, "Blog"))

	// Sign In routes
	goji.Get("/signin", application.Route(controller, "SignIn"))
	goji.Post("/signin", application.Route(controller, "SignInPost"))

	// Sign Up routes
	goji.Get("/signup", application.Route(controller, "SignUp"))
	goji.Post("/signup", application.Route(controller, "SignUpPost"))

	// KTHXBYE
	goji.Get("/logout", application.Route(controller, "Logout"))

	goji.Get("/blog", application.Route(controller, "Blog"))
	goji.Get("/post/:postid", application.Route(controller, "Post"))
	goji.Get("/category/:categoryid", application.Route(controller, "Categories"))
	goji.Get("/page/:pageid", application.Route(controller, "Pages"))

	graceful.PostHook(func() {
		application.Close()
	})
	goji.Serve()
	//http2.ConfigureServer(http, &http2.Server{})
}
Example #17
0
File: main.go Project: silky/rct
func main() {
	directory := flag.String("directory", "/usr/local/rct", "Path to the folder storing RCT experiment data")
	templateDirectory := flag.String("template-directory", "/usr/local/rct/server/templates", "Path to the folder storing RCT server templates (this file -> server/templates)")
	staticDirectory := flag.String("static-directory", "/usr/local/rct/server/static", "Path to the folder storing RCT server templates (this file -> server/static)")

	flag.Parse()
	if len(flag.Args()) > 0 {
		log.Fatalf("Usage: server [-directory DIRECTORY] ")
	}
	h := new(RegexpHandler)
	renderRoute, err := regexp.Compile("/experiments/.*/iterations/.+/.+/render")
	if err != nil {
		log.Fatal(err)
	}
	iterationRoute, err := regexp.Compile("/experiments/.*/iterations/.+/.+")
	if err != nil {
		log.Fatal(err)
	}
	staticRoute, err := regexp.Compile("/static")
	if err != nil {
		log.Fatal(err)
	}
	defaultRoute, err := regexp.Compile("/")
	if err != nil {
		log.Fatal(err)
	}
	h.HandleFunc(renderRoute, renderHandler(*directory, *templateDirectory))
	h.HandleFunc(iterationRoute, newRctHandler(*directory, *templateDirectory))
	h.Handler(staticRoute, http.StripPrefix("/static", http.FileServer(http.Dir(*staticDirectory))))
	h.Handler(defaultRoute, http.FileServer(http.Dir(*directory)))
	allHandlers := jsonStripper(serverHeaderHandler(h))
	log.Fatal(http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, allHandlers)))
}
func main() {

	// Get Hostname
	host, err := getHost()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("School dashboard started.\nConnect at: %v:8080", host)

	// Get database filename
	args := flag.Args()
	filename := "school.db"
	if len(args) >= 1 {
		filename = args[1]
	}

	// Connect to database
	env, err := env.Connect(filename)
	if err != nil {
		log.Fatal(err)
	}

	// Static and Image servers
	static := http.FileServer(http.Dir("./static"))
	images := http.FileServer(http.Dir("./images"))

	// Client Server
	clientMux := http.NewServeMux()
	clientMux.Handle("/static/", http.StripPrefix("/static/", static))
	clientMux.Handle("/images/", http.StripPrefix("/images/", images))
	clientMux.HandleFunc("/", handlers.Index(env))
	clientMux.HandleFunc("/attainmentgroups/", handlers.AttainmentGroups(env))
	clientMux.HandleFunc("/attendance/", handlers.AttendanceExplorer(env))
	clientMux.HandleFunc("/attendancegroups/", handlers.AttendanceGroups(env))
	clientMux.HandleFunc("/basics/", handlers.EnglishAndMaths(env))
	clientMux.HandleFunc("/ebacc/", handlers.EBacc(env))
	clientMux.HandleFunc("/ks3summary/", handlers.KS3Summary(env))
	clientMux.HandleFunc("/ks3groups/", handlers.KS3Groups(env))
	clientMux.HandleFunc("/progress8/", handlers.Progress8(env))
	clientMux.HandleFunc("/progress8groups/", handlers.Progress8Groups(env))
	//clientMux.HandleFunc("/export/headlines/", handlers.ExportHeadlines(env))
	clientMux.HandleFunc("/export/subject/", handlers.ExportSubject(env))
	clientMux.HandleFunc("/subjects/", handlers.SubjectOverview(env))
	clientMux.HandleFunc("/progressgrid/", handlers.ProgressGrid(env))
	clientMux.HandleFunc("/subjectgroups/", handlers.SubjectGroups(env))
	clientMux.HandleFunc("/student/", handlers.Student(env))
	clientMux.HandleFunc("/search/", handlers.Search(env))
	for {
		err := http.ListenAndServe(":8080", clientMux)
		log.Println(err)
	}

	/*
		adminMux := http.NewServeMux()
		adminMux.Handle("/static/", http.StripPrefix("/static/", static))
		adminMux.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello") })
		http.ListenAndServe(":8081", adminMux)
	*/

}
Example #19
0
func init() {
	http.HandleFunc("/", handler)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css/"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img/"))))
	tpl = template.Must(template.ParseGlob("*.html"))
}
Example #20
0
func BuildContentFor(root string, prod bool, cnts []*content, cfg *config.Config) (http.Handler, error) {
	if prod {
		for _, cnt := range cnts {
			if err := cnt.renderToFile(filepath.Join(root, cnt.dest), root, cfg, prod); err != nil {
				return nil, err
			}
		}

		return http.FileServer(http.Dir(root)), nil
	}

	m := map[string]*content{}
	for _, cnt := range cnts {
		if strings.HasSuffix(cnt.dest, "index.html") {
			m[path.Clean("/"+filepath.Dir(cnt.dest)+"/")] = cnt
		} else {
			m["/"+cnt.dest] = cnt
		}
	}

	return &devHandler{
		Handler: http.FileServer(http.Dir(root)),
		root:    root,
		cfg:     cfg,
		content: m,
	}, nil
}
func main() {
	flag.Parse()
	s, err := susigo.NewSusi(*susiaddr, *cert, *key)
	if err != nil {
		log.Printf("Error while creating susi connection: %v", err)
		return
	}
	susi = s
	log.Println("successfully create susi connection")
	sessionTimeouts = make(map[string]time.Time)

	if *user == "" && *pass == "" {
		http.HandleFunc("/publish", publishHandler)
		http.HandleFunc("/upload", uploadHandler)
		http.Handle("/ws", websocket.Handler(websocketHandler))
		http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))))
		http.HandleFunc("/", redirectToIndex)
	} else {
		http.HandleFunc("/publish", BasicAuth(publishHandler))
		http.HandleFunc("/upload", BasicAuth(uploadHandler))
		http.HandleFunc("/ws", BasicAuth(websocket.Handler(websocketHandler).ServeHTTP))
		http.HandleFunc("/assets/", BasicAuth(http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))).ServeHTTP))
		http.HandleFunc("/", BasicAuth(redirectToIndex))
	}

	log.Printf("starting http server on %v...", *webaddr)
	if *useHTTPS {
		log.Fatal(http.ListenAndServeTLS(*webaddr, *cert, *key, context.ClearHandler(http.DefaultServeMux)))
	} else {
		log.Fatal(http.ListenAndServe(*webaddr, context.ClearHandler(http.DefaultServeMux)))
	}
}
Example #22
0
func NewRouter(config *RouterConfig) *mux.Router {
	router := mux.NewRouter()
	apiRouter := router.PathPrefix("/api").Subrouter()

	// load routes
	for _, route := range GetRoutes(config.Handlers) {
		var handler http.Handler

		handler = route.HandlerFunc
		handler = Logger(handler, route.Name)

		apiRouter.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}

	// serve static assets (user images, etc)
	assetsFs := http.FileServer(http.Dir(config.Handlers.AssetsDir))
	router.PathPrefix("/assets").Handler(http.StripPrefix("/assets/", assetsFs))

	// serve admin client files (html, css, etc)
	adminFs := http.FileServer(http.Dir(config.AdminDir))
	router.PathPrefix("/").Handler(adminFs)

	return router
}
Example #23
0
func NewApp() Middleware {
	router := NewRouter()

	router.Handle("GET", "/", HandleHome)
	router.Handle("GET", "/register", HandleUserNew)
	router.Handle("POST", "/register", HandleUserCreate)
	router.Handle("GET", "/login", HandleSessionNew)
	router.Handle("POST", "/login", HandleSessionCreate)
	router.Handle("GET", "/image/:imageID", HandleImageShow)
	router.Handle("GET", "/user/:userID", HandleUserShow)

	router.ServeFiles(
		"/assets/*filepath",
		http.Dir("assets/"),
	)
	router.ServeFiles(
		"/im/*filepath",
		http.Dir("data/images/"),
	)

	secureRouter := NewRouter()
	secureRouter.Handle("GET", "/sign-out", HandleSessionDestroy)
	secureRouter.Handle("GET", "/account", HandleUserEdit)
	secureRouter.Handle("POST", "/account", HandleUserUpdate)
	secureRouter.Handle("GET", "/images/new", HandleImageNew)
	secureRouter.Handle("POST", "/images/new", HandleImageCreate)

	middleware := Middleware{}
	middleware.Add(router)
	middleware.Add(http.HandlerFunc(RequireLogin))
	middleware.Add(secureRouter)

	return middleware
}
Example #24
0
File: run.go Project: jeffjen/podd
func init() {
	s := api.GetServeMux()

	// Register static polymer assets
	asset_repo := api.Dir{
		http.Dir("html/bower_components/"),
		http.Dir("html/custom_components/"),
	}
	s.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(asset_repo)))

	// Register static html resources
	s.Handle("/css", http.FileServer(http.Dir("html/www/css/")))
	s.Handle("/js", http.FileServer(http.Dir("html/www/js/")))
	s.Handle("/", http.FileServer(http.Dir("html/www/")))

	// API for cluster
	s.HandleFunc("/cluster/list", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "html/www/cluster-list.json")
	})
	// API for service
	s.HandleFunc("/service/list", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "html/www/service-list.json")
	})

	s.HandleFunc("/info", dsc.Info)
}
Example #25
0
func main() {

	var portNumber int
	flag.IntVar(&portNumber, "port", 80, "Default port is 80")
	flag.Parse()

	// Routes to serve front-end assets
	r := mux.NewRouter()
	http.Handle("/javascripts/", http.StripPrefix("/javascripts/", http.FileServer(http.Dir("frontend/public/javascripts/"))))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("frontend/public/images/"))))
	http.Handle("/stylesheets/", http.StripPrefix("/stylesheets/", http.FileServer(http.Dir("frontend/public/stylesheets/"))))

	// API Endpoints
	r.PathPrefix(V1_PREFIX + "/run-ad-on/{service}/for/{stream}").HandlerFunc(ads.AdRequester)
	r.Path(V1_PREFIX + "/ping").HandlerFunc(health.Ping)

	// Pass to front-end
	r.PathPrefix(V1_PREFIX + "/stream").HandlerFunc(index)
	r.PathPrefix(V1_PREFIX).HandlerFunc(index)

	http.Handle("/", r)
	port := strconv.FormatInt(int64(portNumber), 10)
	fmt.Println("IRWIn Server starting")
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Could not start on port "+port, err)
	}
}
Example #26
0
func main() {
	dashr_ip := flag.String("fqdn", "127.0.0.1", "IP/FQDN to run HTTP listener at")
	dashr_port := flag.String("http", "8001", "port to run HTTP listener at")
	www_data := flag.String("www", "www-data", "path to ansible dashr static site content")
	ansible_setup := flag.String("ansible", "dummy-ansible-files", "path to ansible setup root of Playbooks, Roles Dir")
	dashr_config := flag.String("config", "config", "path to fetch/save Config used by Static Site Content")
	flag.Parse()

	connection_string := fmt.Sprintf("%s:%s", *dashr_ip, *dashr_port)
	www_data_uri := fmt.Sprintf("/%s/", *www_data)
	ansible_setup_uri := fmt.Sprintf("/%s/", *ansible_setup)
	dashr_config_uri := fmt.Sprintf("/%s/", *dashr_config)

	dashr_fs := http.FileServer(http.Dir(*www_data))
	http.Handle(www_data_uri, http.StripPrefix(www_data_uri, dashr_fs))

	ansible_fs := http.FileServer(http.Dir(*ansible_setup))
	http.Handle(ansible_setup_uri, http.StripPrefix(ansible_setup_uri, ansible_fs))

	config_fs := http.FileServer(http.Dir(*dashr_config))
	http.Handle(dashr_config_uri, http.StripPrefix(dashr_config_uri, config_fs))

	http.HandleFunc("/", redirect)
	log.Println("Ansible Dashr @", connection_string)
	if err := http.ListenAndServe(connection_string, nil); err != nil {
		fmt.Println("ERROR: Failed to start server.", err.Error())
	}
}
Example #27
0
File: server.go Project: Juerd/Up1
func main() {
	http.HandleFunc("/", index)
	http.HandleFunc("/up", upload)
	http.HandleFunc("/del", delfile)
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("static"))))
	http.Handle("/i/", http.StripPrefix("/i", http.FileServer(http.Dir("i"))))

	config = readConfig()
	validateConfig(config)

	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		defer wg.Done()
		if config.Http.Enabled {
			log.Printf("Starting HTTP server on %s\n", config.Http.Listen)
			log.Println(http.ListenAndServe(config.Http.Listen, nil))
		}
	}()

	go func() {
		defer wg.Done()
		if config.Https.Enabled {
			log.Printf("Starting HTTPS server on %s\n", config.Https.Listen)
			log.Println(http.ListenAndServeTLS(config.Https.Listen, config.Https.Cert, config.Https.Key, nil))
		}
	}()

	wg.Wait()
}
Example #28
0
func main() {
	mux := http.NewServeMux()
	Admin.MountTo("/admin", mux)

	// frontend routes
	router := gin.Default()
	router.LoadHTMLGlob("templates/*")

	// serve static files
	router.StaticFS("/system/", http.Dir("public/system"))
	router.StaticFS("/assets/", http.Dir("public/assets"))

	// books
	bookRoutes := router.Group("/books")
	{
		// listing
		bookRoutes.GET("", controllers.ListBooksHandler)
		bookRoutes.GET("/", controllers.ListBooksHandler) // really? i need both of those?...
		// single book - product page
		bookRoutes.GET("/:id", controllers.ViewBookHandler)
	}

	mux.Handle("/", router)

	// handle login and logout of users
	mux.HandleFunc("/login", controllers.LoginHandler)
	mux.HandleFunc("/logout", controllers.LogoutHandler)

	// start the server
	http.ListenAndServe(":9000", mux)
}
Example #29
0
File: main.go Project: Onills/CS130
func main() {
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
	http.Handle("/pic/", http.StripPrefix("/pic/", http.FileServer(http.Dir("pic"))))

	http.HandleFunc("/", surfer)
	http.ListenAndServe(":8080", nil)
}
Example #30
0
func main() {

	// serve static files and the latest ango.js
	http.Handle("/", http.FileServer(http.Dir("./files")))
	http.Handle("/ango.js", http.FileServer(http.Dir("../")))

	// create and setup new provider
	p := ango.NewProvider()
	p.BeforeWebsocket = func(w http.ResponseWriter, r *http.Request) bool {
		log.Printf("new incomming connection!")
		return true
	}
	p.Debug = true

	p.RegisterProcedureFunc("getStuff", func(data json.RawMessage, def *ango.Deferred) {
		// create SomeStuff
		stuff := SomeStuff{
			Foo: "foo",
			Bar: "bar",
		}

		// resolve defered with stuff
		def.Resolve(stuff)
	})

	// hook provider onto a custom url
	http.Handle("/ango-websocket", p)

	// listen and serve
	http.ListenAndServe(":8123", nil)
}