当前位置: 首页>>代码示例>>Golang>>正文


Golang http.FileServer函数代码示例

本文整理汇总了Golang中net/http.FileServer函数的典型用法代码示例。如果您正苦于以下问题:Golang FileServer函数的具体用法?Golang FileServer怎么用?Golang FileServer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了FileServer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

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)
}
开发者ID:josephlewis42,项目名称:autopilot,代码行数:33,代码来源:web_program.go

示例2: main

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()
}
开发者ID:Juerd,项目名称:Up1,代码行数:31,代码来源:server.go

示例3: main

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)
	}
}
开发者ID:alytvynov,项目名称:goa,代码行数:31,代码来源:example.go

示例4: main

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

}
开发者ID:ngaut,项目名称:realtimetraffic,代码行数:28,代码来源:main.go

示例5: main

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)
	}
}
开发者ID:paulgrock,项目名称:ipl-irwin,代码行数:27,代码来源:irwin-server.go

示例6: init

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"))
}
开发者ID:ph3ng,项目名称:CSCI-130-Spring-16,代码行数:7,代码来源:main.go

示例7: main

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)))
	}
}
开发者ID:webvariants,项目名称:susi-gowebstack,代码行数:32,代码来源:susi-webstack.go

示例8: main

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{})
}
开发者ID:prashanthrv,项目名称:sangeeblog,代码行数:60,代码来源:server.go

示例9: main

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

}
开发者ID:andrewcharlton,项目名称:school-dashboard,代码行数:60,代码来源:dashboard.go

示例10: init

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

}
开发者ID:bpeng,项目名称:walking-md,代码行数:33,代码来源:main.go

示例11: main

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)
}
开发者ID:computermatt,项目名称:QSL-Card-Showcase,代码行数:34,代码来源:main.go

示例12: main

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)
	}
}
开发者ID:bamnet,项目名称:shuttle_tracking_2,代码行数:28,代码来源:main.go

示例13: listen

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()
	}
}
开发者ID:nyxtom,项目名称:usda,代码行数:26,代码来源:webserver.go

示例14: main

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
}
开发者ID:nesv,项目名称:uhttpd,代码行数:31,代码来源:main.go

示例15: main

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)))
}
开发者ID:silky,项目名称:rct,代码行数:33,代码来源:main.go


注:本文中的net/http.FileServer函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。