Golang FileServer示例

说明

golang fileserver示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: web_program.go 项目: josephlewis42/autopilot

func main() {

	err := GenerateFolders()
	fmt.Println(err)

	includepath, _ := filepath.Abs("./static/")

	http.Handle("/inc/", http.StripPrefix("/inc/", http.FileServer(http.Dir(includepath))))
	http.HandleFunc("/log/download/", AutopilotDownloader)
	http.HandleFunc("/log/delete/", GenericDeleter("./autopilot/runs/"))
	http.HandleFunc("/autopilot/upload/", GenericUploader("./autopilot/pilots/"))
	http.HandleFunc("/autopilot/delete/", GenericDeleter("./autopilot/pilots/"))
	http.HandleFunc("/autopilot/start/", StartAutopilot)
	http.HandleFunc("/autopilot/stop/", StopAutopilot)
	http.HandleFunc("/configuration/upload/", GenericUploader("./autopilot/configurations/"))
	http.HandleFunc("/configuration/delete/", GenericDeleter("./autopilot/configurations/"))
	http.HandleFunc("/configuration/edit/", EditConfiguration)
	http.HandleFunc("/command/shutdown/", GenericCommand("/sbin/shutdown", "-H", "-P", "now"))
	http.HandleFunc("/command/proc/", GenericCommand("/bin/ps", "-aux"))
	http.HandleFunc("/command/ifconfig/", GenericCommand("/sbin/ifconfig"))
	http.HandleFunc("/command/dmesg/", GenericCommand("/bin/dmesg"))
	http.HandleFunc("/command/w/", GenericCommand("/usr/bin/w"))
	http.HandleFunc("/command/cpuinfo/", GenericCommand("/bin/cat", "/proc/cpuinfo"))

	http.Handle("/configuration/download/", http.StripPrefix("/configuration/download/", http.FileServer(http.Dir("./autopilot/configurations/"))))
	http.Handle("/autopilot/download/", http.StripPrefix("/autopilot/download/", http.FileServer(http.Dir("./autopilot/pilots/"))))

	http.HandleFunc("/", rootHandler)

	fmt.Println("Running")
	err = http.ListenAndServe("localhost:9000", nil)
	fmt.Println(err)
}

示例#2
文件: server.go 项目: 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()
}

示例#3
文件: example.go 项目: alytvynov/goa

func main() {
	if err := goa.Init(goa.Config{
		LoginPage:     "/login.html",
		HashKey:       []byte(hashKey),
		EncryptionKey: []byte(cryptoKey),
		CookieName:    "session",
		PQConfig:      "user=test_user password=test_pass dbname=goa",
	}); err != nil {
		log.Println(err)
		return
	}

	// public (no-auth-required) files
	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
	// protected files, only for logged-in users
	http.Handle("/protected/", goa.NewHandler(http.StripPrefix("/protected/", http.FileServer(http.Dir("protected")))))
	// home handler
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "index.html")
	})
	http.HandleFunc("/login.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "login.html")
	})
	http.HandleFunc("/register.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "register.html")
	})

	if err := http.ListenAndServeTLS(":8080", "keys/cert.pem", "keys/key.pem", nil); err != nil {
		log.Println(err)
	}
}

示例#4
文件: main.go 项目: ngaut/realtimetraffic

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)
	}

}

示例#5
文件: irwin-server.go 项目: paulgrock/ipl-irwin

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)
	}
}

示例#6
文件: main.go 项目: ph3ng/CSCI-130-Spring-16

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"))
}

示例#7
文件: susi-webstack.go 项目: webvariants/susi-gowebstack

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)))
	}
}

示例#8
文件: server.go 项目: prashanthrv/sangeeblog

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{})
}

示例#9
文件: dashboard.go 项目: andrewcharlton/school-dashboard

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)
	*/

}

示例#10
文件: main.go 项目: bpeng/walking-md

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

}

示例#11
文件: main.go 项目: computermatt/QSL-Card-Showcase

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)
}

示例#12
文件: main.go 项目: bamnet/shuttle_tracking_2

func main() {
	// close Mongo session when server terminates
	defer App.Session.Close()

	// Start auto updater
	go App.UpdateShuttles(Config.DataFeed, Config.UpdateInterval)

	// Routing
	r := mux.NewRouter()
	r.HandleFunc("/", IndexHandler).Methods("GET")
	r.HandleFunc("/admin", AdminHandler).Methods("GET")
	r.HandleFunc("/admin/{*}", AdminHandler).Methods("GET")
	r.HandleFunc("/vehicles", App.VehiclesHandler).Methods("GET")
	r.HandleFunc("/vehicles/create", App.VehiclesCreateHandler).Methods("POST")
	r.HandleFunc("/updates", App.UpdatesHandler).Methods("GET")
	r.HandleFunc("/routes", App.RoutesHandler).Methods("GET")
	r.HandleFunc("/routes/create", App.RoutesCreateHandler).Methods("POST")
	r.HandleFunc("/stops", App.StopsHandler).Methods("GET")
	r.HandleFunc("/stops/create", App.StopsCreateHandler).Methods("POST")
	// Static files
	r.PathPrefix("/bower_components/").Handler(http.StripPrefix("/bower_components/", http.FileServer(http.Dir("bower_components/"))))
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
	// Serve requests
	http.Handle("/", r)
	if err := http.ListenAndServe(":8080", r); err != nil {
		log.Fatalf("Unable to ListenAndServe: %v", err)
	}
}

示例#13
文件: webserver.go 项目: nyxtom/usda

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()
	}
}

示例#14
文件: main.go 项目: 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
}

示例#15
文件: main.go 项目: 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)))
}

示例#16
文件: main.go 项目: jerryz1982/Hound

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
}

示例#17
文件: service_endpoint.go 项目: pkdevboxy/query

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))))
}

示例#18
文件: web.go 项目: yujinqiu/gotrace

// StartServer generates webpage, serves it via http
// and tries to open it using default browser.
func StartServer(bind string, data []byte, params *Params) error {
	// Serve data as data.js
	http.HandleFunc("/data.js", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("var data = "))
		w.Write(data)
	}))

	// Serve params as params.js
	http.HandleFunc("/params.js", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("var params = "))
		data, err := json.MarshalIndent(params, "", "  ")
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintln(os.Stderr, "[ERROR] failed to render params:", err)
			return
		}
		w.Write(data)
	}))

	// Handle static files
	if devMode {
		var fs http.FileSystem
		fs = http.Dir("page")
		http.Handle("/", http.FileServer(fs))
	} else {
		http.Handle("/", http.FileServer(assetFS()))
	}
	go StartBrowser("http://localhost" + bind)

	return http.ListenAndServe(bind, nil)
}

示例#19
文件: serve.go 项目: prattmic/codesearch

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)
}

示例#20
文件: router.go 项目: JordietYahii/rango

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
}

示例#21
文件: ui.go 项目: kdevroede/camlistore

// makeClosureHandler returns a handler to serve Closure files.
// root is either:
// 1) empty: use the Closure files compiled in to the binary (if
//    available), else redirect to the Internet.
// 2) a URL prefix: base of Camlistore to get Closure to redirect to
// 3) a path on disk to the root of camlistore's source (which
//    contains the necessary subset of Closure files)
func makeClosureHandler(root, handlerName string) (http.Handler, error) {
	// devcam server environment variable takes precedence:
	if d := os.Getenv("CAMLI_DEV_CLOSURE_DIR"); d != "" {
		log.Printf("%v: serving Closure from devcam server's $CAMLI_DEV_CLOSURE_DIR: %v", handlerName, d)
		return http.FileServer(http.Dir(d)), nil
	}
	if root == "" {
		fs, err := closurestatic.FileSystem()
		if err == os.ErrNotExist {
			log.Printf("%v: no configured setting or embedded resources; serving Closure via %v", handlerName, closureBaseURL)
			return closureBaseURL, nil
		}
		if err != nil {
			return nil, fmt.Errorf("error loading embedded Closure zip file: %v", err)
		}
		log.Printf("%v: serving Closure from embedded resources", handlerName)
		return http.FileServer(fs), nil
	}
	if strings.HasPrefix(root, "http") {
		log.Printf("%v: serving Closure using redirects to %v", handlerName, root)
		return closureRedirector(root), nil
	}

	path := filepath.Join("third_party", "closure", "lib", "closure")
	return makeFileServer(root, path, filepath.Join("goog", "base.js"))
}

示例#22
文件: run.go 项目: 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)
}

示例#23
文件: frontend.go 项目: sdgoij/TheDistributedBay

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)
	}
}

示例#24
文件: template.go 项目: Xackery/shinshop

func Index(w http.ResponseWriter, r *http.Request) {
	var err error

	type Index struct {
		*Site
	}

	resp := Index{
		Site: SiteInit(),
	}

	if r.URL.Path != "/" {
		log.Println("Request to", r.URL.Path)
		if isProduction {
			http.FileServer(assetFS()).ServeHTTP(w, r)
		} else {
			http.FileServer(http.Dir("webserver/web")).ServeHTTP(w, r)
		}
		return
	}

	//resp := someStruct{}
	err = contentTemplate["index/index"].Execute(w, resp)
	if err != nil {
		log.Println("Error executing index", err.Error())
	}
}

示例#25
文件: main.go 项目: ChrisKaufmann/feedinator-go

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)
}

示例#26
文件: dashr.go 项目: vdesjardins/ansible-dashr

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())
	}
}

示例#27
文件: gore.go 项目: importre/gore

func init() {
	initTemplate()
	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/find/", findHandler)
	http.Handle("/css/", http.FileServer(http.Dir(".")))
	http.Handle("/js/", http.FileServer(http.Dir(".")))
}

示例#28
文件: app.go 项目: geoct826/goblog

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)
}

示例#29
文件: main.go 项目: 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)
}

示例#30
文件: main.go 项目: nav01/CSCI-130

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)
}

展开阅读全文