當前位置: 首頁>>代碼示例>>Golang>>正文


Golang http.FileServer函數代碼示例

本文整理匯總了Golang中http.FileServer函數的典型用法代碼示例。如果您正苦於以下問題:Golang FileServer函數的具體用法?Golang FileServer怎麽用?Golang FileServer使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了FileServer函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Serve

func Serve() {
	log.Printf("Starting web server at %v...", config.Conf.HTTPServeAddr)

	http.Handle("/", &sessionView{&tplView{"/", "home", homeView}})
	for _, page := range Info.ExtraPages {
		http.Handle("/"+page, &sessionView{&tplView{"/" + page, page, homeView}})
	}

	http.Handle("/login", &sessionView{&tplView{"/login", "login", loginView}})
	http.Handle("/register", &sessionView{&tplView{"/register", "register", registerView}})
	http.Handle("/logout", &sessionView{&redirectView{"/logout", logoutView}})
	http.Handle("/settings", &sessionView{&tplView{"/settings", "settings", settingsView}})

	http.Handle("/go_study/", &sessionView{&redirectView{"", goStudyView}})
	http.Handle("/study_home", &sessionView{&tplView{"/study_home", "study_home", studyHomeView}})
	http.Handle("/browse/", &sessionView{&tplView{"", "browse", browseView}})
	http.Handle("/chunk_summary/", &sessionView{&tplView{"", "chunk_summary", chunkSummaryView}})
	http.Handle("/chunk_read/", &sessionView{&tplView{"", "chunk_read", chunkSummaryView}})
	http.Handle("/go_chunk/", &sessionView{&redirectView{"", goChunkView}})

	http.Handle("/srs_home", &sessionView{&tplView{"/srs_home", "srs_home", srsHomeView}})
	http.Handle("/srs_activate/", &sessionView{&redirectView{"", srsActivateView}})
	http.Handle("/srs_deactivate/", &sessionView{&redirectView{"", srsDeactivateView}})
	http.Handle("/srs_review/", &sessionView{&tplView{"", "srs_review_drill", srsReviewView}})
	http.Handle("/srs_tomorrow_drill/", &sessionView{&tplView{"", "srs_review_drill", srsTomorrowView}})
	http.Handle("/chunk_drill/", &sessionView{&tplView{"", "srs_review_drill", srsChunkDrillView}})
	http.Handle("/lesson_drill/", &sessionView{&tplView{"", "srs_review_drill", srsLessonDrillView}})
	http.Handle("/srs_save", &sessionView{&jsonView{"/srs_save", srsSaveView}})

	http.Handle("/dic", &sessionView{&tplView{"/dic", "dic_results", dicSearchView}})

	http.Handle("/image/", http.FileServer(config.Conf.WebFolder, ""))
	http.Handle("/style/", http.FileServer(config.Conf.WebFolder, ""))
	http.Handle("/js/", http.FileServer(config.Conf.WebFolder, ""))
	http.Handle("/media/", http.FileServer(config.Conf.ContentsFolder, ""))

	http.Handle("/reload_tpl", &sessionView{&redirectView{"/reload_tpl",
		func(req *http.Request, s *session) string {
			LoadWebFiles()
			return req.FormValue("back")
		}}})
	http.Handle("/reload_data", &sessionView{&redirectView{"/reload_data",
		func(req *http.Request, s *session) string {
			contents.Info, contents.Levels, contents.LevelsMap = contents.LoadData()
			return req.FormValue("back")
		}}})

	err := http.ListenAndServe(config.Conf.HTTPServeAddr, nil)
	if err != nil {
		log.Fatalf("Error while starting HTTP server : %v", err)
	}
}
開發者ID:Alexis211,項目名稱:ajstk,代碼行數:52,代碼來源:webs.go

示例2: main

func main() {
	err := loadTemplates()
	if err != nil {
		fmt.Println(err)
		return
	}

	homepage = "<a href=\"/sim/10/1/1\">Basic Simulation</a><br /><table><tr><td>SpawnTime</td><td>10 mins</tr><tr><td># Nurses</td><td>1</td></tr><tr><td># Doctors</td><td>1</td></tr></table>"

	// Simulation
	wd, err := os.Getwd()
	if err != nil {
		log.Println("ERROR: Failed to get Working Directory", err)
		return
	}

	//indexHtml, err := ioutil.ReadFile(wd + "/assets/index.html")
	//if err != nil { fmt.Println("ERROR:", err); return; }

	http.Handle("/assets/", http.FileServer(wd, ""))
	http.HandleFunc("/sim/", http.HandlerFunc(SimulationHandler))
	http.HandleFunc("/", http.HandlerFunc(HomeHandler))

	err = http.ListenAndServe(":6060", nil)
	log.Println("LOG: Server Shutting Down")

	if err != nil {
		log.Println("ERROR:", err)
	}

}
開發者ID:ghthor,項目名稱:hospitSim.go,代碼行數:31,代碼來源:main.go

示例3: main

func main() {
	sio := socketio.NewSocketIO(nil)

	sio.OnConnect(func(c *socketio.Conn) {
		sio.Broadcast("connected: socket.io/" + c.String())
	})

	sio.OnDisconnect(func(c *socketio.Conn) {
		sio.BroadcastExcept(c, "disconnected: socket.io/"+c.String())
	})

	sio.OnMessage(func(c *socketio.Conn, msg socketio.Message) {
		sio.BroadcastExcept(c, msg.Data())
	})

	go func() {
		count := 0
		for {
			sio.Broadcast(fmt.Sprintf("ping%d", count))
			count++
			syscall.Sleep(1e9)
		}
	}()

	mux := sio.ServeMux()
	mux.Handle("/", http.FileServer("www/", "/"))
	if err := http.ListenAndServe(":8080", mux); err != nil {
		fmt.Println("ListenAndServe:", err)
	}
}
開發者ID:kosta,項目名稱:go-test,代碼行數:30,代碼來源:main.go

示例4: StartHtmlHandler

// starts http handlers for HTML content based on the given configuration file
// optional parameters:  default.contentDirectory (location of html content to be served at https://example.com/ or https://example.com/html/index.html
func StartHtmlHandler() {
	if contentDir, _ := configFile.GetString("default", "contentDirectory"); contentDir != "" {
		logger.Printf("StartHtmlHandler(): serving HTML content from [%v]", contentDir)
		http.Handle("/html/", http.StripPrefix("/html/", http.FileServer(http.Dir(contentDir))))
		http.Handle("/", http.RedirectHandler("/html/", http.StatusTemporaryRedirect))
	}
}
開發者ID:codeforsystemsbiology,項目名稱:restjsonmgo.go,代碼行數:9,代碼來源:main.go

示例5: BenchmarkStaticFileOverHTTPWithMultiplex

func BenchmarkStaticFileOverHTTPWithMultiplex(b *testing.B) {
	b.StopTimer()
	var C = 50 // number of simultaneous clients
	http.Handle("/static/", http.FileServer("_test/", "/static"))
	if err := createStaticTestFile(); err != nil {
		log.Print("Failed to create test file:", err)
		return
	}
	weblisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("net.Listen error:", err)
		return
	}
	url := "http://" + weblisten.Addr().String() + "/static/fcgi_test.html"
	go http.Serve(weblisten, nil)

	// allow this many simultaneous connections to the webserver
	start := make(chan bool, C)
	for i := 0; i < C; i++ {
		start <- true
	}
	done := make(chan bool, b.N) // for syncing all the multiplex goroutines
	b.StartTimer()
	log.Print("Loop starting...", b.N)
	for i := 0; i < b.N; i++ {
		go func(index int) {
			<-start
			defer func() {
				done <- true
				start <- true
			}()
			response, _, err := http.Get(url)
			if err != nil {
				log.Print("http.Get error:", err)
			}
			if response == nil {
				log.Print("Nil response.")
				return
			}
			if response.StatusCode != 200 {
				log.Print("Bad response status:", response.StatusCode)
				return
			}
			if response != nil {
				body, err := ioutil.ReadAll(response.Body)
				if err != nil {
					log.Print("ioutil.ReadAll error:", err)
					return
				}
				b.SetBytes(int64(len(body)))
				response.Body.Close()
			}
		}(i)
	}
	for i := 0; i < b.N; i++ {
		<-done
	}
	weblisten.Close()
	removeStaticTestFile()
}
開發者ID:gnanderson,項目名稱:fcgigo,代碼行數:60,代碼來源:oldtests.go

示例6: main

func main() {
	flag.Parse()

	auth.AccessPassword = os.Getenv("CAMLI_PASSWORD")
	if len(auth.AccessPassword) == 0 {
		fmt.Fprintf(os.Stderr,
			"No CAMLI_PASSWORD environment variable set.\n")
		os.Exit(1)
	}

	{
		fi, err := os.Stat(*flagStorageRoot)
		if err != nil || !fi.IsDirectory() {
			fmt.Fprintf(os.Stderr,
				"Storage root '%s' doesn't exist or is not a directory.\n",
				*flagStorageRoot)
			os.Exit(1)
		}
	}

	blobFetcher = newDiskStorage(*flagStorageRoot)

	ws := webserver.New()
	ws.HandleFunc("/", handleRoot)
	ws.HandleFunc("/camli/", handleCamli)
	ws.Handle("/js/", http.FileServer("../../clients/js", "/js/"))
	ws.Serve()
}
開發者ID:marsch,項目名稱:camlistore,代碼行數:28,代碼來源:camlistored.go

示例7: main

func main() {
	log.SetFlags(0)
	flag.Parse()

	cgiHandler := &cgi.Handler{
		Path: *cgitPath,
		Env:  []string{},
		InheritEnv: []string{
			"CGIT_CONFIG",
		},
	}
	if *config != "" {
		cgiHandler.Env = append(cgiHandler.Env,
			"CGIT_CONFIG="+*config)
	}

	fs := http.FileServer(http.Dir(*cgitRes))
	http.Handle("/cgit.css", fs)
	http.Handle("/cgit.png", fs)
	http.Handle("/", cgiHandler)

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

	// Everything seems to work: daemonize (close file handles)
	os.Stdin.Close()
	os.Stdout.Close()
	os.Stderr.Close()
}
開發者ID:Luit-IT,項目名稱:gitwrap,代碼行數:31,代碼來源:main.go

示例8: main

func main() {
	mode := flag.Int("mode", 0, "0: Broadcast, 1: LIFO, 2: FILO")
	flag.Parse()

	config := pusher.DefaultConfiguration
	config.GCInterval = 0 // disable garbage collecting
	config.ConcurrencyMode = *mode

	// Create a new pusher context, where all publisher and subscriber
	// locations are statically mapped to "static"-channel.
	push := pusher.New(pusher.StaticAcceptor("static"), config)
	http.Handle("/pub", push.PublisherHandler)
	http.Handle("/sub", push.SubscriberHandler)
	http.Handle("/", http.FileServer("www/", "/"))

	// Create the "static"-channel explictly, since AllowChannelCreation is false
	// in the DefaultConfiguration.
	channel, _ := push.Channel("static")

	go func() {
		i := 0
		for {
			channel.PublishString(fmt.Sprintf("--- Greetings from the server #%d ---", i), false)
			time.Sleep(10e9)
			i++
		}
	}()

	log.Print("Tune your browser tab(s) to http://localhost:8080/")

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}
開發者ID:andradeandrey,項目名稱:pusher.go,代碼行數:34,代碼來源:example.go

示例9: main

func main() {
	flag.Parse()
	readTemplates()

	if *root == "" {
		var err os.Error
		*root, err = os.Getwd()
		if err != nil {
			log.Exitf("Failed to getwd: %v", err)
		}
	}

	mux := http.DefaultServeMux
	mux.Handle("/favicon.ico", http.FileServer(path.Join(*root, "static"), "/"))
	mux.Handle("/robots.txt", http.FileServer(path.Join(*root, "static"), "/"))
	mux.Handle("/static/", http.FileServer(path.Join(*root, "static"), "/static/"))

	testCgi := &CgiHandler{ExecutablePath: path.Join(*root, "test.cgi"),
		Root: "/test.cgi",
	}
	mux.Handle("/test.cgi", testCgi)
	mux.Handle("/test.cgi/foo", testCgi)

	mux.Handle("/code", http.RedirectHandler("/code/", http.StatusFound))
	if *gitwebScript != "" {
		env := os.Environ()
		env = append(env, "GITWEB_CONFIG="+path.Join(*root, "gitweb-camli.conf"))
		env = append(env, "CAMWEB_ROOT="+path.Join(*root))
		mux.Handle("/code/", &gitwebHandler{
			Cgi: &CgiHandler{
				ExecutablePath: *gitwebScript,
				Root:           "/code/",
				Environ:        env,
			},
			Static: http.FileServer(*gitwebFiles, "/code/"),
		})
	}
	mux.HandleFunc("/", mainHandler)

	var handler http.Handler = &noWwwHandler{Handler: mux}
	if *logDir != "" || *logStdout {
		handler = NewLoggingHandler(handler, *logDir, *logStdout)
	}
	if err := http.ListenAndServe(*httpAddr, handler); err != nil {
		log.Exitf("ListenAndServe %s: %v", *httpAddr, err)
	}
}
開發者ID:marsch,項目名稱:camlistore,代碼行數:47,代碼來源:camweb.go

示例10: newPublishFromConfig

func newPublishFromConfig(ld blobserver.Loader, conf jsonconfig.Obj) (h http.Handler, err os.Error) {
	ph := &PublishHandler{
		bsLoader: ld,
	}
	ph.RootName = conf.RequiredString("rootName")
	ph.JSFiles = conf.OptionalList("js")
	ph.CSSFiles = conf.OptionalList("css")
	blobRoot := conf.RequiredString("blobRoot")
	searchRoot := conf.RequiredString("searchRoot")
	cachePrefix := conf.OptionalString("cache", "")
	bootstrapSignRoot := conf.OptionalString("devBootstrapPermanodeUsing", "")
	if err = conf.Validate(); err != nil {
		return
	}

	if ph.RootName == "" {
		return nil, os.NewError("invalid empty rootName")
	}

	bs, err := ld.GetStorage(blobRoot)
	if err != nil {
		return nil, fmt.Errorf("publish handler's blobRoot of %q error: %v", blobRoot, err)
	}
	ph.Storage = bs

	si, err := ld.GetHandler(searchRoot)
	if err != nil {
		return nil, fmt.Errorf("publish handler's searchRoot of %q error: %v", searchRoot, err)
	}
	var ok bool
	ph.Search, ok = si.(*search.Handler)
	if !ok {
		return nil, fmt.Errorf("publish handler's searchRoot of %q is of type %T, expecting a search handler",
			searchRoot, si)
	}

	if bootstrapSignRoot != "" {
		if t := ld.GetHandlerType(bootstrapSignRoot); t != "jsonsign" {
			return nil, fmt.Errorf("publish handler's devBootstrapPermanodeUsing must be of type jsonsign")
		}
		h, _ := ld.GetHandler(bootstrapSignRoot)
		jsonSign := h.(*JSONSignHandler)
		if err := ph.bootstrapPermanode(jsonSign); err != nil {
			return nil, fmt.Errorf("error bootstrapping permanode: %v", err)
		}
	}

	if cachePrefix != "" {
		bs, err := ld.GetStorage(cachePrefix)
		if err != nil {
			return nil, fmt.Errorf("publish handler's cache of %q error: %v", cachePrefix, err)
		}
		ph.Cache = bs
	}

	ph.staticHandler = http.FileServer(uiFiles)

	return ph, nil
}
開發者ID:ipeet,項目名稱:camlistore,代碼行數:59,代碼來源:publish.go

示例11: BenchmarkStaticFileOverTCPNoMultiplex

func BenchmarkStaticFileOverTCPNoMultiplex(b *testing.B) {
	b.StopTimer()
	fcgiMux := http.NewServeMux()
	fcgiMux.Handle("/static/", http.FileServer("_test/", "/static"))
	if err := createStaticTestFile(); err != nil {
		log.Print("Failed to create test file:", err)
		return
	}
	tcplisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("Listen error:", err)
		return
	}
	weblisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("net.Listen error:", err)
		return
	}
	url := "http://" + weblisten.Addr().String() + "/static/fcgi_test.html"
	handler, err := Handler([]Dialer{
		NewDialer("tcp", tcplisten.Addr().String()),
	})
	if err != nil {
		log.Print("Handler error:", err)
		return
	}
	http.Handle("/static/", handler)
	go http.Serve(tcplisten, fcgiMux)
	go http.Serve(weblisten, nil)
	b.StartTimer()
	log.Print("Loop starting...", b.N)
	for i := 0; i < b.N; i++ {
		response, _, err := http.Get(url)
		if err != nil {
			log.Print("http.Get error:", err)
		}
		if response == nil {
			log.Print("Nil response.")
			continue
		}
		if response.StatusCode != 200 {
			log.Print("Bad response status:", response.StatusCode)
			continue
		}
		if response != nil {
			_, err := ioutil.ReadAll(response.Body)
			if err != nil {
				log.Print("ioutil.ReadAll error:", err)
				break
			}
			response.Body.Close()
			// b.SetBytes(int64(len(body)))
		}
	}
	weblisten.Close()
	tcplisten.Close()
	removeStaticTestFile()
}
開發者ID:gnanderson,項目名稱:fcgigo,代碼行數:58,代碼來源:oldtests.go

示例12: main

func main() {
	http.Handle("/echo", websocket.Handler(EchoServer))
	http.Handle("/lobby", websocket.Handler(LobbyServer))
	http.Handle("/", http.FileServer(http.Dir("/tmp")))
	fmt.Println("Listening on:", listenAddress)
	if err := http.ListenAndServe(listenAddress, nil); err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
開發者ID:uglybrd,項目名稱:GoGameHTML5,代碼行數:9,代碼來源:server.go

示例13: main

// view example at http://localhost:8080/ with firebug console
// ext docs at http://localhost:8080/ext/docs/
// for go docs run "godoc -http=:6060" and hit http://localhost:6060/
func main() {
	http.Handle("/api/", direct.Api(&direct.Provider{
		Url:       "/router/",
		Type:      "remoting",
		Namespace: "App.remote",
	}))
	http.Handle("/router/", direct.Router(map[string]direct.Action{
		"example":     &action{},
		"exampleForm": &formAction{},
	}))
	http.Handle("/js/", http.FileServer("example", "/js/"))
	http.Handle("/ext/", http.FileServer(EXTJSROOT, "/ext/"))
	http.Handle("/", newHandler())
	log.Stdout("Listening on :8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Exit(err.String())
	}
}
開發者ID:bedwards,項目名稱:goextdirect,代碼行數:22,代碼來源:example.go

示例14: main

func main() {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		fmt.Printf("%s\n", err)
		os.Exit(1)
	}

	fmt.Printf("%d\n", l.Addr().(*net.TCPAddr).Port)

	http.Handle("/", http.FileServer(http.Dir(".")))
	http.Serve(l, nil)
}
開發者ID:soundcloud,項目名稱:statiker,代碼行數:12,代碼來源:main.go

示例15: main

// TODO: figure out live reloading for Handlers? Is this easily possible?
func main() {
	flag.Parse();
	runtime.GOMAXPROCS(*maxprocs);
	// TODO: use a map datastructure of some type? nah. this works.
	// BUG?: "/" basically passes everything which doesn't match anything else :(
	http.Handle("/", http.HandlerFunc(DEFAULT));
	http.Handle("/twitter/replies", http.HandlerFunc(TWITTER_REPLIES));
	http.Handle("/login/twitter", http.HandlerFunc(LOGIN_TWITTER));
	http.Handle("/callback/twitter", http.HandlerFunc(CALLBACK_TWITTER));
	http.Handle("/login/yahoo", http.HandlerFunc(LOGIN_YAHOO));
	http.Handle("/callback/yahoo", http.HandlerFunc(CALLBACK_YAHOO));
	http.Handle("/login/google", http.HandlerFunc(LOGIN_GOOGLE));
	http.Handle("/callback/google", http.HandlerFunc(CALLBACK_GOOGLE));
	http.Handle("/logout", http.HandlerFunc(LOGOUT));
	http.Handle("/static/", http.FileServer("./static/", "/static/"));
	http.Handle("/favicon.ico", http.FileServer("./static/", "/"));
	err := http.ListenAndServe(*addr, nil);
	if err != nil {
		log.Exit("ListenAndServe:", err);
	}
}
開發者ID:montsamu,項目名稱:go-twitter-oauth,代碼行數:22,代碼來源:example.go


注:本文中的http.FileServer函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。