// 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))
	}
}
Beispiel #2
0
func startServer() {
	http.Handle("/echo", Handler(echoServer))
	http.Handle("/echoDraft75", Draft75Handler(echoServer))
	server := httptest.NewServer(nil)
	serverAddr = server.Listener.Addr().String()
	log.Print("Test WebSocket server listening on ", serverAddr)
}
Beispiel #3
0
func init() {
	fmt.Println("Selog filekkkk")
	http.Handle("/index", http.HandlerFunc(Render))
	http.Handle("/index.ghtml", http.HandlerFunc(RenderGoPagesForbidden))

	http.Handle("/", http.HandlerFunc(func(conn http.ResponseWriter, request *http.Request) {
		if request.URL.Path == "/" {
			defaultPage := "index"
			if strings.TrimSpace(defaultPage) != "" {
				http.Redirect(conn, defaultPage, 307)
			}
			return
		}
		val := "src" + request.URL.Path
		input, err := os.OpenFile(val, os.O_RDONLY, 0666)
		//		input,err := os.Open(val)
		if err != nil {
			conn.WriteHeader(404)
			conn.Write([]byte("<h1>404 Not Found</h1>"))
			return
		}
		s, _ := input.Stat()
		conn.Header.Set("Content-Length", fmt.Sprintf("%d(MISSING)", s.Size))
		//	conn.SetHeader("Content-Type", mime.TypeByExtension(strings.ToLower(path.Ext(val))))
		fmt.Sprintf("%d(MISSING)", s.Size)
		mime.TypeByExtension(strings.ToLower(path.Ext(val)))

		conn.WriteHeader(200)
		http.ServeFile(conn, request, val)
	}))
	http.Handle("/src", http.HandlerFunc(RenderGoPagesForbidden))
	http.Handle("/pages", http.HandlerFunc(RenderGoPagesForbidden))

}
Beispiel #4
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()
}
Beispiel #5
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)
	}
}
Beispiel #6
0
func main() {
	flag.Parse()
	runtime.GOMAXPROCS(*threads)

	http.Handle("/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
	http.Handle("/pprof/heap", http.HandlerFunc(pprof.Heap))
	http.Handle("/pprof/symbol", http.HandlerFunc(pprof.Symbol))
	go func() {
		http.ListenAndServe("0.0.0.0:6060", nil)
	}()

	if *accesslog != "" {
		logf, err := os.OpenFile(*accesslog, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0644)
		if err != nil {
			log.Print("open " + *accesslog + " failed")
			return
		}
		memcache.AccessLog = log.New(logf, "", log.Ldate|log.Ltime)
	} else if *debug {
		memcache.AccessLog = log.New(os.Stdout, "", log.Ldate|log.Ltime)
	}

	tbefore := int64(0)
	if *before != "" {
		t, err := time.Parse(time.RFC3339[:len(*before)], *before)
		if err != nil {
			log.Print("parse time error", err.String())
			return
		}
		t.ZoneOffset = 8 * 60 * 60
		tbefore = t.Seconds()
		log.Print("load data before", t.Format(time.RFC3339))
	}

	log.Print("start to open db ", *dbpath)
	store := NewStore(*dbpath, *dbdepth, tbefore)
	defer store.Close()

	addr := fmt.Sprintf("%s:%d", *listen, *port)
	s := memcache.NewServer(store)
	e := s.Listen(addr)
	if e != nil {
		log.Print("Listen at ", *listen, "failed")
		return
	}

	// monitor mem usage
	go func() {
		ul := uint64(*memlimit) * 1024 * 1024
		for runtime.MemStats.HeapSys < ul {
			time.Sleep(1e9)
		}
		log.Print("Mem used by Go is over limitation ", runtime.MemStats.HeapSys/1024/1024, *memlimit)
		s.Shutdown()
	}()

	s.Serve()
	log.Print("shut down gracefully.")
}
Beispiel #7
0
func main() {
	http.Handle("/admin", http.HandlerFunc(admin))
	http.Handle("/banana", http.HandlerFunc(banana))
	err := http.ListenAndServe(":11118", nil)
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
}
Beispiel #8
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())
	}
}
Beispiel #9
0
func Serve(listener net.Listener) {
	http.HandleFunc("/", viewHtml)
	http.HandleFunc("/$stats.html", statsHtml)
	http.Handle("/$main.js", stringHandler{"application/javascript", main_js})
	http.Handle("/$main.css", stringHandler{"text/css", main_css})
	http.HandleFunc("/$events/", evServer)

	http.Serve(listener, nil)
}
Beispiel #10
0
func main() {
	fmt.Printf("Starting http Server ... ")
	http.Handle("/args", http.HandlerFunc(ArgServer))
	http.Handle("/hello", http.HandlerFunc(sayHello))
	http.Handle("/sine", http.HandlerFunc(sineServer))
	err := http.ListenAndServe("0.0.0.0:8080", nil)
	if err != nil {
		fmt.Printf("ListenAndServe Error :" + err.String())
	}
}
Beispiel #11
0
func main() {
	http.Handle("/blog", http.HandlerFunc(views.Index))
	http.Handle("/blog/entry/add", http.HandlerFunc(views.AddEntry))
	http.Handle("/blog/entry/", http.HandlerFunc(views.Entry))
	http.Handle("/blog/comment/add", http.HandlerFunc(views.AddComment))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
}
func startServer() {
	l, e := net.Listen("tcp", "127.0.0.1:0") // any available address
	if e != nil {
		log.Exitf("net.Listen tcp :0 %v", e)
	}
	serverAddr = l.Addr().String()
	log.Print("Test WebSocket server listening on ", serverAddr)
	http.Handle("/echo", Handler(echoServer))
	http.Handle("/echoDraft75", Draft75Handler(echoServer))
	go http.Serve(l, nil)
}
Beispiel #13
0
func main() {
	flag.Parse()
	http.Handle("/circle/", http.HandlerFunc(circle))
	http.Handle("/rect/", http.HandlerFunc(rect))
	http.Handle("/arc/", http.HandlerFunc(arc))
	http.Handle("/text/", http.HandlerFunc(text))
	err := http.ListenAndServe(*port, nil)
	if err != nil {
		log.Println("ListenAndServe:", err)
	}
}
Beispiel #14
0
func Serve(listener net.Listener) {
	prefix := "/d/" + ClusterName
	evPrefix = "/events" + prefix

	http.Handle("/", http.RedirectHandler("/view/d/"+ClusterName+"/", 307))
	http.HandleFunc("/view/", viewHtml)
	http.Handle("/main.js", stringHandler{"application/javascript", main_js})
	http.Handle("/main.css", stringHandler{"text/css", main_css})
	http.HandleFunc(evPrefix+"/", evServer)

	http.Serve(listener, nil)
}
Beispiel #15
0
func Run(addr string) {
	// Configure the delimiters
	// Parse the file once
	statsTempl.SetDelims("<?", "?>")
	statsTempl.ParseFile(statsTemplatePath)

	http.Handle("/stats", http.HandlerFunc(Stats))
	http.Handle("/add/", http.HandlerFunc(Add))
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Beispiel #16
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())
	}
}
Beispiel #17
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())
	}
}
Beispiel #18
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())
	}
}
Beispiel #19
0
// We export a single function, which creates a page controlled by a
// single websocket.  It's quite primitive, and yet quite easy to use!
func HandleChans(url string, handler func(evts <-chan string, pages chan<- string, done <-chan os.Error)) {
	myh := func(ws *websocket.Conn) {
		evts := make(chan string)
		pages := make(chan string)
		done := make(chan os.Error)
		go handler(evts, pages, done)
		go func() {
			r := bufio.NewReader(ws)
			for {
				x, err := r.ReadString('\n')
				if err == nil {
					evts <- x[:len(x)-1]
				} else {
					done <- os.NewError("Error from r.ReadString: " + err.String())
					return
				}
			}
		}()
		for {
			x := <-pages
			_, err := fmt.Fprintln(ws, x)
			if err != nil {
				done <- os.NewError("Error in fmt.Fprintln: " + err.String())
				return
			}
		}
	}
	http.Handle(path.Join(url, "socket"), websocket.Handler(myh))

	skeleton := func(c http.ResponseWriter, req *http.Request) {
		c.SetHeader("Content-Type", "text/html")
		fmt.Fprintln(c, skeletonpage(req))
	}
	http.HandleFunc(url, skeleton)
}
Beispiel #20
0
func main() {
	http.Handle("/echo", websocket.Handler(EchoServer))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
Beispiel #21
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()
}
Beispiel #22
0
// We export a single function, which creates a page controlled by a
// single websocket.  It's quite primitive, and yet quite easy to use!
func HandleSeparate(url string, hh func() Handler) {
	myh := func(ws *websocket.Conn) {
		h := hh()
		h.AddSend(func(p string) { fmt.Fprintln(ws, p) })
		fmt.Fprintln(ws, "start")
		r := bufio.NewReader(ws)
		for {
			x, err := r.ReadString('\n')
			if err == nil {
				h.Handle(x[:len(x)-1])
			} else {
				h.Done(os.NewError("Error from r.ReadString: " + err.String()))
				return
			}
		}
	}
	http.Handle(path.Join(url, "socket"), websocket.Handler(myh))

	skeleton := func(c http.ResponseWriter, req *http.Request) {
		c.Header().Set("Content-Type", "text/html")
		fmt.Fprintln(c, skeletonpage(req))
	}
	http.HandleFunc(url, skeleton)

}
Beispiel #23
0
func main() {
	if len(os.Args) > 1 {
		upass = os.Args[1]
	}
	t := time.UTC()
	initend = isodatestring(t)
	initbegin = isodatestring(time.SecondsToUTC(t.Seconds() -
		(secondsPerDay * maxDays)))
	showparams("init")
	http.Handle("/users/", http.HandlerFunc(tfusers))
	http.Handle("/list/", http.HandlerFunc(tflist))
	err := http.ListenAndServe(":1958", nil)
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
}
Beispiel #24
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)
	}

}
Beispiel #25
0
func main() {
	http.Handle("/", http.HandlerFunc(PushServer))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
}
Beispiel #26
0
func main() {
	http.Handle("/", createServer())
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.String())
	}
}
Beispiel #27
0
func main() {
	flag.Parse()
	http.Handle("/", http.HandlerFunc(QR))
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Beispiel #28
0
func main() {
	flag.Parse()
	go hub()
	http.Handle("/broadcast", websocket.Handler(clientHandler))
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Beispiel #29
0
func main() {
	fmt.Printf("http://localhost:1978/hello\n")
	http.Handle("/hello", http.HandlerFunc(HelloServer))
	err := http.ListenAndServe(":1978", nil)
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
}
Beispiel #30
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()
}