Exemplo n.º 1
11
// 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))
	}
}
Exemplo n.º 2
0
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)
	}
}
Exemplo n.º 3
0
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)
	}

}
Exemplo n.º 4
0
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)
	}
}
Exemplo n.º 5
0
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()
}
Exemplo n.º 6
0
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()
}
Exemplo n.º 7
0
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()
}
Exemplo n.º 8
0
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)
	}
}
Exemplo n.º 9
0
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)
	}
}
Exemplo n.º 10
0
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
}
Exemplo n.º 11
0
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()
}
Exemplo n.º 12
0
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())
	}
}
Exemplo n.º 13
0
// 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())
	}
}
Exemplo n.º 14
0
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)
}
Exemplo n.º 15
0
// 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);
	}
}
Exemplo n.º 16
0
func main() {
	wd, _ := os.Getwd()

	handler := new(Rot13FileServerHandler)
	handler.h = http.FileServer(wd+"/httpdoc", "")

	err := http.ListenAndServe(":12345", handler)

	if err != nil {
		fmt.Println("ListenAndServe error: ", err)
	}
}
Exemplo n.º 17
0
func main() {
	port := "0.0.0.0:8080"
	room = NewRoom()
	staticDir := http.Dir("/projects/go/chat/static")
	staticServer := http.FileServer(staticDir)

	http.HandleFunc("/", Home)
	http.HandleFunc("/feed", FeedMux)
	http.HandleFunc("/login", LoginMux)
	http.Handle("/static/", http.StripPrefix("/static", staticServer))
	fmt.Printf("Serving at %s ----------------------------------------------------", port)
	http.ListenAndServe(port, nil)
}
Exemplo n.º 18
0
Arquivo: ergo.go Projeto: wezm/ergo
func main() {
	// Determine execuable dir
	execpath, err := exec.LookPath(os.Args[0])
	if err != nil {
		log.Exitf("Unable to determine executable path")
	}
	// Absolutise execpath: Seems the best way in absence of Realpath
	if pwd, err := os.Getwd(); err == nil {
		execpath = pathutil.Clean(pathutil.Join(pwd, execpath))
	} else {
		log.Exitf("Getwd: %s", err)
	}
	execdir, _ := pathutil.Split(execpath)

	tmplroot = flag.String("root", pathutil.Join(execdir, "templates"), "root directory for templates")
	flag.Parse()
	log.Stdoutf("Using template dir: %s", *tmplroot)
	readTemplates()

	http.Handle("/", http.HandlerFunc(func(c *http.Conn, req *http.Request) {}))
	http.Handle("/add", http.HandlerFunc(func(c *http.Conn, req *http.Request) {
		// Process the add template
		var buf bytes.Buffer
		/*    if err := parseerrorHTML.Execute(errors, &buf); err != nil {*/
		err := addHTML.Execute("x", &buf)
		if err != nil {
			log.Stderrf("addHTML.Execute: %s", err)
		}
		//templ.Execute(req.FormValue("s"), c);
		servePage(c, "Add", "", string(buf.Bytes()))
	}))
	http.Handle("/css/", http.FileServer("public/css", "/css/"))
	http.Handle("/js/", http.FileServer("public/js", "/js/"))

	err = http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemplo n.º 19
0
/**
* Main Function
 */
func main() {
	fmt.Printf("Starting http Server ... \n")

	http.Handle("/$sys", http.HandlerFunc(handleSys))
	http.Handle("/$db", http.HandlerFunc(handleDb))

	//internal webserver should be disabled
	http.Handle("/", http.FileServer(http.Dir("web/")))

	err := http.ListenAndServe("127.0.0.1:8080", nil)
	if err != nil {
		fmt.Printf("ListenAndServe Error :" + err.String())
	}
}
Exemplo n.º 20
0
func initHandlers() {
	paths := filepath.SplitList(*pkgPath)
	for _, t := range build.Path {
		if t.Goroot {
			continue
		}
		paths = append(paths, t.SrcDir())
	}
	fsMap.Init(paths)

	fileServer = http.FileServer(fsHttp)
	cmdHandler = httpHandler{"/cmd/", filepath.Join(*goroot, "src", "cmd"), false}
	pkgHandler = httpHandler{"/pkg/", filepath.Join(*goroot, "src", "pkg"), true}
}
Exemplo n.º 21
0
//Start the web server
func runServer(port string, s chan int) {

	http.HandleFunc("/", viewHandle)
	http.HandleFunc("/logview/", logViewHandle)

	pwd, _ := os.Getwd()
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(pwd+"/static/"))))

	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		println(err.String())
	}

	s <- 1
}
Exemplo n.º 22
0
func main() {
	flag.Parse()
	if *help {
		flag.PrintDefaults()
		return
	}

	coord := NewDownloadCoordinator()
	http.Handle("/dl", NewDownloadHandler(*basePath, coord))
	//	http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(*basePath))))
	http.Handle("/", http.FileServer(http.Dir("fs/")))
	if e := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil); e != nil {
		fmt.Printf("Cannot listen! Error: %s\n", e.String())
	}
}
Exemplo n.º 23
0
func main() {
	flag.Parse()
	ts, err := tiles.Load(*tilesPath)
	if err != nil {
		panic(err.String())
	}

	http.Handle("/gettile", ts)
	http.Handle("/", http.FileServer("./static", ""))
	fmt.Println("Serving on ", *httpPort, "...")
	err = http.ListenAndServe(*httpPort, nil)
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
}
Exemplo n.º 24
0
func main() {
	flag.Parse()

	// source of unique numbers
	go func() {
		for i := 0; ; i++ {
			uniq <- i
		}
	}()

	// set archChar
	var err os.Error
	archChar, err = build.ArchChar(runtime.GOARCH)
	if err != nil {
		log.Fatal(err)
	}

	// find and serve the go tour files
	t, _, err := build.FindTree(basePkg)
	if err != nil {
		log.Fatalf("Couldn't find tour files: %v", err)
	}
	root := filepath.Join(t.SrcDir(), basePkg)
	root := basePkg
	log.Println("Serving content from", root)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/favicon.ico" || r.URL.Path == "/" {
			fn := filepath.Join(root, "static", r.URL.Path[1:])
			http.ServeFile(w, r, fn)
			return
		}
		http.Error(w, "not found", 404)
	})
	http.Handle("/static/", http.FileServer(http.Dir(root)))
	http.HandleFunc("/kill", kill)

	// set include path for ld and gc
	pkgDir = t.PkgDir()

	if !strings.HasPrefix(*httpListen, "127.0.0.1") &&
		!strings.HasPrefix(*httpListen, "localhost") {
		log.Print(localhostWarning)
	}

	log.Printf("Serving at http://%s/", *httpListen)
	log.Fatal(http.ListenAndServe(*httpListen, nil))
}
Exemplo n.º 25
0
// A very simple chat server
func main() {
	buffer := new(vector.Vector)
	mutex := new(sync.Mutex)

	// create the socket.io server and mux it to /socket.io/
	config := socketio.DefaultConfig
	config.Origins = []string{"localhost:8080"}
	sio := socketio.NewSocketIO(&config)

	go func() {
		if err := sio.ListenAndServeFlashPolicy(":843"); err != nil {
			log.Println(err)
		}
	}()

	// when a client connects - send it the buffer and broadcasta an announcement
	sio.OnConnect(func(c *socketio.Conn) {
		mutex.Lock()
		c.Send(Buffer{buffer.Copy()})
		mutex.Unlock()
		sio.Broadcast(Announcement{"connected: " + c.String()})
	})

	// when a client disconnects - send an announcement
	sio.OnDisconnect(func(c *socketio.Conn) {
		sio.Broadcast(Announcement{"disconnected: " + c.String()})
	})

	// when a client send a message - broadcast and store it
	sio.OnMessage(func(c *socketio.Conn, msg socketio.Message) {
		payload := Message{[]string{c.String(), msg.Data()}}
		mutex.Lock()
		buffer.Push(payload)
		mutex.Unlock()
		sio.Broadcast(payload)
	})

	log.Println("Server starting. Tune your browser to http://localhost:8080/")

	mux := sio.ServeMux()
	mux.Handle("/", http.FileServer(http.Dir("www/")))

	if err := http.ListenAndServe(":8080", mux); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Exemplo n.º 26
0
func main() {
	client.Addr = "localhost:6379"

	// create the socket.io server and mux it to /socket.io/
	config := socketio.DefaultConfig
	config.Origins = []string{"*"}
	sio = socketio.NewSocketIO(&config)

	sio.OnConnect(socketIOConnectHandler)
	sio.OnDisconnect(socketIODisconnectHandler)
	sio.OnMessage(socketIOMessageHandler)

	mux := sio.ServeMux()
	mux.Handle("/", http.FileServer("static/", "/"))
	if err := http.ListenAndServe(":80", mux); err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Exemplo n.º 27
0
// Initialize HTTP server for frontend
func ListenAndServeHttp(backend appchilada.Backend) os.Error {
	http.HandleFunc("/", indexHandler(backend))
	http.HandleFunc("/show/", showHandler(backend))

	if dir, err := os.Getwd(); err != nil {
		return err
	} else {
		dir = dir + string(os.PathSeparator) + "assets"
		log.Printf("Opening webserver in %s", dir)
		// Handle static files in /public served on /public (stripped prefix)
		http.Handle("/assets/", http.StripPrefix("/assets", http.FileServer(http.Dir(dir))))
	}
	log.Printf("Opening webserver on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		return err
	}
	return nil
}
Exemplo n.º 28
0
func main() {
	flag.Parse()
	runtime.GOMAXPROCS(*Procs)
	//	port := 8082
	//	host := "130.226.133.44:8082"
	host := *(Host) + ":" + fmt.Sprint(*(Port))
	mux := dynamichttp.NewServeMux()
	dir := http.Dir("./www")
	mux.Handle("/", http.FileServer(dir))

	wshttp.EnableWsHttp(host, mux)

	fmt.Println("Running on " + host)
	err := dynamichttp.ListenAndServe(host, mux)
	if err != nil {
		fmt.Println("error", err)
	}
	fmt.Println("Bye!")
}
Exemplo n.º 29
0
func startAllServers(t *testing.T) (tcplisten, unixlisten, weblisten net.Listener) {
	var fcgiMux = http.NewServeMux()
	// define the muxer for the FCGI responders to use
	fcgiMux.Handle("/hello/", http.HandlerFunc(HelloServer))
	fcgiMux.Handle("/notfound/", http.HandlerFunc(http.NotFound))
	fcgiMux.Handle("/connection/", http.HandlerFunc(func(conn http.ResponseWriter, req *http.Request) {
		conn.SetHeader("Connection", "keep-alive")
		io.WriteString(conn, "connection test")
	}))
	fcgiMux.Handle("/static/", http.FileServer("_test", "/static"))
	if err := createStaticTestFile(); err != nil {
		t.Fatal(err)
		return
	}
	// then start the responders
	tcplisten, _ = net.Listen("tcp", ":0")
	go Serve(tcplisten, fcgiMux)
	unixlisten, _ = net.Listen("unix", "_test/unixsocket")
	go Serve(unixlisten, fcgiMux)

	// define the muxer for the http server to use
	// (all requests go to the pool of listeners)
	wd, _ := os.Getwd()
	handler, err := Handler([]Dialer{
		NewDialer("tcp", tcplisten.Addr().String()),
		NewDialer("unix", unixlisten.Addr().String()),
		NewDialer("exec", wd+"/_test/listener_test_exec.out"),
	})
	if err != nil {
		t.Fatal(err)
		return
	}
	webMux := http.NewServeMux()
	webMux.Handle("/", handler)

	// start the web server
	weblisten, _ = net.Listen("tcp", ":0")
	go http.Serve(weblisten, webMux)

	// return all the data
	return tcplisten, unixlisten, weblisten
}
Exemplo n.º 30
0
func main() {
	runtime.GOMAXPROCS(8)
	port := "0.0.0.0:8000"
	room = NewRoom()
	rolloffs = make([]*RollOff, 0)
	staticDir := http.Dir("/projects/go/chat/static")
	staticServer := http.FileServer(staticDir)
	homeTemplate = template.Must(template.ParseFile("templates/index.html"))

	http.HandleFunc("/", LogWrap(Home, "Home"))
	http.HandleFunc("/feed", LogWrap(FeedMux, "FeedMux"))
	http.HandleFunc("/login", LogWrap(LoginMux, "LoginMux"))
	http.HandleFunc("/users", LogWrap(GetUsers, "GetUsers"))
	http.HandleFunc("/roll", LogWrap(Roll, "Roll"))
	http.HandleFunc("/roll-off", LogWrap(NewRollOff, "NewRollOff"))
	http.HandleFunc("/roll-off-entry/", LogWrap(EnterRollOff, "EnterRollOff"))
	http.Handle("/static/", http.StripPrefix("/static", staticServer))
	fmt.Printf("Serving at %s ----------------------------------------------------\n", port)
	http.ListenAndServe(port, nil)
}