Exemplo n.º 1
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.º 2
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))

}
Exemplo n.º 3
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.")
}
Exemplo n.º 4
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())
	}
}
Exemplo n.º 5
0
Arquivo: hello.go Projeto: wtaysom/tau
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())
	}
}
Exemplo n.º 6
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())
	}
}
Exemplo n.º 7
0
Arquivo: websvg.go Projeto: johan/svgo
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)
	}
}
Exemplo n.º 8
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)
	}
}
Exemplo n.º 9
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.º 10
0
func Start(ch *chan int, st *State.State) {
	world = *ch
	state = st
	go http.ListenAndServe(":25560", http.HandlerFunc(httpServe))
	go http.ListenAndServe(":25561", websocket.Handler(wssServe))
	//	os.ForkExec("http://localhost:25560/index.oc", []string{}, []string{}, "", []*os.File{})
}
Exemplo n.º 11
0
func main() {
	http.Handle("/", http.HandlerFunc(PushServer))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
}
Exemplo n.º 12
0
Arquivo: wtf.go Projeto: J5lx/luminous
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())
	}
}
Exemplo n.º 13
0
func serveTestFiles(t *testing.T) (l net.Listener, err os.Error) {
	foundValidPort := false
	var port_str string
	for !foundValidPort {
		port := (rand.Int() & 0x7FFF) + 0x08000
		port_str = strconv.Itoa(port)
		addr, err := net.ResolveTCPAddr("127.0.0.1:" + port_str)
		if err != nil {
			t.Error("Create TCP Address: ", err.String())
			return nil, err
		}
		l, err = net.ListenTCP("tcp4", addr)
		if err != nil {
			if err == os.EADDRINUSE || strings.LastIndex(err.String(), os.EADDRINUSE.String()) != -1 {
				continue
			}
			t.Error("Unable to listen on TCP port: ", err.String())
			return l, err
		}
		foundValidPort = true
	}
	OverrideRapleafHostPort("127.0.0.1", port_str)
	go http.Serve(l, http.HandlerFunc(ServeTestHTTP))
	return l, err
}
Exemplo n.º 14
0
func view(prefix string) http.Handler {
	f := func(w http.ResponseWriter, r *http.Request) {
		c := appengine.NewContext(r)
		p := r.URL.Path[len(prefix):]
		if p == "" {
			p = "index"
		}
		s := new(Page)
		k := datastore.NewKey(c, "string", p, 0, nil)
		if item, err := memcache.Get(c, p); err == memcache.ErrCacheMiss {
			datastore.Get(c, k, s)
			err = memcache.Set(c, &memcache.Item{Key: p, Value: []byte(s.Content)})
			if err != nil {
				panic(err)
			}
		} else if err != nil {
			panic(err)
		} else {
			s.Content = string(item.Value)
		}
		output := string(blackfriday.MarkdownCommon([]byte(s.Content)))
		viewTemplate.Execute(w, Foo{p, output, ""})
	}
	return http.HandlerFunc(f)
}
Exemplo n.º 15
0
func (c *WsHttpCore) RegisterWsHttpHandler(id string, pattern string, methods []string) os.Error {
	if c.lookupConn(id) == nil {
		log.Println("Connection not found!", id)
		return os.NewError("connection not found")
	}
	if strings.HasPrefix(pattern, "/meta/wsconnections") {
		log.Println("Request to get async notifications about connections")
		c.AddConnectionListener(c.lookupConn(id), id)
		//c.DispatchResponse([]byte("true"),nil,connid,r.Id)
		// }
		return nil
	}

	handler := getHandlerFor(pattern, c.mux)
	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rsp, err := c.SendReceive(id, r)
		if err != nil {
			w.WriteHeader(500)
			log.Println(pattern, "handling error", err)
			return
		}
		w.Write(rsp)
		return
	})
	for _, meth := range methods {
		handler.Add(meth, id, fn)
	}
	c.onDisconnect(id, func() {
		handler.RemoveAll(id, []string{})
	})
	log.Println("RegisterWsHttpHandler done")
	return nil
}
Exemplo n.º 16
0
// where prefix is like "/" or "/s3/" for e.g. "/camli/" or "/s3/camli/*"
func makeCamliHandler(prefix, baseURL string, storage blobserver.Storage) http.Handler {
	if !strings.HasSuffix(prefix, "/") {
		panic("expected prefix to end in slash")
	}
	baseURL = strings.TrimRight(baseURL, "/")

	storageConfig := &storageAndConfig{
		storage,
		&blobserver.Config{
			Writable: true,
			Readable: true,
			IsQueue:  false,
			URLBase:  baseURL + prefix[:len(prefix)-1],
		},
	}
	return http.HandlerFunc(func(conn http.ResponseWriter, req *http.Request) {
		action, err := parseCamliPath(req.URL.Path[len(prefix)-1:])
		if err != nil {
			log.Printf("Invalid request for method %q, path %q",
				req.Method, req.URL.Path)
			unsupportedHandler(conn, req)
			return
		}
		handleCamliUsingStorage(conn, req, action, storageConfig)
	})
}
Exemplo n.º 17
0
func (s *S) SetUpSuite(c *gocheck.C) {
	go func() {
		http.Handle("/html.html", http.HandlerFunc(htmlHandler))
		http.Handle("/bin.bin", http.HandlerFunc(binHandler))
		http.Handle("/post", http.HandlerFunc(postHandler))
		http.Handle("/404.html", http.NotFoundHandler())
		http.Handle("/cookie.html", http.HandlerFunc(cookieHandler))
		http.Handle("/redirect/", http.HandlerFunc(redirectHandler))
		fmt.Printf("\nRunning test server on http://localhost:54123\n")
		if err := http.ListenAndServe(":54123", nil); err != nil {
			c.Fatalf("Cannot run test server on port: %s", err.String())
		}
	}()
	time.Sleep(2e8)
	c.Succeed()
}
Exemplo n.º 18
0
func main( )
{
	rpc.HandleHTTP();

	l, _ := net.Listen("tcp", ":8089");
	http.Serve(l, http.HandlerFunc( handleRequest ) );
}
Exemplo n.º 19
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())
	}
}
Exemplo n.º 20
0
func main() {
	flag.Parse()
	http.Handle("/", http.HandlerFunc(QR))
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Exemplo n.º 21
0
//runs the web application and serves http requests
func Run(addr string) {
	http.Handle("/", http.HandlerFunc(httpHandler))

	log.Stdoutf("web.go serving %s", addr)
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemplo n.º 22
0
func main() {
	log.Println("Starting up")

	flag.Parse()
	streamHost = fmt.Sprintf("scribe-%s.local.yelpcorp.com:3535", *aggregator)
	log.Println("Connecting to ", streamHost)

	go listenTCPClients()

	http.Handle("/", http.HandlerFunc(ServePage))
	http.Handle("/lookup", http.HandlerFunc(ServeDataItemPage))
	http.Handle("/ws", websocket.Handler(ServeWS))

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
Exemplo n.º 23
0
func http_main() {
	//Process the http commands
	fmt.Printf("Starting http Server ... ")
	http.Handle("/", http.HandlerFunc(sayHello))
	err := http.ListenAndServe("0.0.0.0:8080", nil)
	if err != nil {
		fmt.Printf("ListenAndServe Error", err)
	}
}
Exemplo n.º 24
0
func main() {
  req_channel = make(chan CRequest);
  go CHelloServer(req_channel);
  http.Handle("/hello", http.HandlerFunc(HelloServer));
  err := http.ListenAndServe(":12345", nil);
  if err != nil {
   panic("ListenAndServe: ", err.String())
  }
}
Exemplo n.º 25
0
func main() {
	flag.Parse()
	fmt.Println("Hello, world")
	http.Handle("/", handlerWrapper(http.HandlerFunc(testpage)))
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		fmt.Println("Oh noes.")
	}
}
Exemplo n.º 26
0
func registerRequestHandlers() {
	http.Handle("/marvin/coins/", http.HandlerFunc(genericHttpPostRequestHandler))
	http.Handle("/marvin/registration/", http.HandlerFunc(genericHttpPostRequestHandler))
	http.Handle("/marvin/unregister/", http.HandlerFunc(genericHttpPostRequestHandler))
	http.Handle("/marvin/messages/", http.HandlerFunc(genericHttpPostRequestHandler))
	http.Handle("/marvin/scores/", http.HandlerFunc(genericHttpPostRequestHandler))
	http.Handle("/marvin/achievements/", http.HandlerFunc(genericHttpPostRequestHandler))
	http.Handle("/marvin/leaderboard/", http.HandlerFunc(genericHttpPostRequestHandler))

	http.Handle("/", http.HandlerFunc(genericInvalidRequestHandler))
}
Exemplo n.º 27
0
func BenchmarkHelloWorldOverHTTPWithMultiplex(b *testing.B) {
	b.StopTimer()
	var C = 50 // number of simultaneous clients
	http.Handle("/hello/", http.HandlerFunc(func(conn http.ResponseWriter, req *http.Request) { conn.Write(helloWorldBytes) }))
	weblisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("net.Listen error:", err)
		return
	}
	url := "http://" + weblisten.Addr().String() + "/hello/"
	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()
}
Exemplo n.º 28
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.º 29
0
func main() {
	flag.Parse()

	// The counter is published as a variable directly.
	ctr := new(Counter)
	http.Handle("/counter", ctr)
	expvar.Publish("counter", ctr)

	http.Handle("/", http.HandlerFunc(Logger))
	http.Handle("/go/", http.FileServer(*webroot, "/go/"))
	http.Handle("/flags", http.HandlerFunc(FlagServer))
	http.Handle("/args", http.HandlerFunc(ArgServer))
	http.Handle("/go/hello", http.HandlerFunc(HelloServer))
	http.Handle("/chan", ChanCreate())
	http.Handle("/date", http.HandlerFunc(DateServer))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Panicln("ListenAndServe:", err)
	}
}
Exemplo n.º 30
0
//Runs the web application and serves http requests
func (s *Server) Run(addr string) {
	s.initServer()

	mux := http.NewServeMux()

	mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
	mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
	mux.Handle("/debug/pprof/heap", http.HandlerFunc(pprof.Heap))
	mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
	mux.Handle("/", s)

	s.Logger.Printf("web.go serving %s\n", addr)

	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
	s.l = l
	err = http.Serve(s.l, mux)
	s.l.Close()
}