Esempio n. 1
1
// Serve the website. This function blocks.
func serveWebsite() {
	port := 8080

	// Sanity check to make sure we're in the right directory.
	_, err := os.Stat("static/font.png")
	if err != nil {
		log.Fatal("You must be in the trs80 source directory (github.com/lkesteloot/trs80)")
	}

	// Create handlers.
	handlers := http.NewServeMux()
	handlers.Handle("/", webutil.GetHandler(http.HandlerFunc(homeHandler)))
	handlers.Handle("/ws", websocket.Handler(wsHandler))
	handlers.Handle("/static/", http.StripPrefix("/static/",
		http.FileServer(http.Dir("static"))))

	// Create server.
	address := fmt.Sprintf(":%d", port)
	server := http.Server{
		Addr:           address,
		Handler:        webutil.LoggingHandler(handlers),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: http.DefaultMaxHeaderBytes,
	}

	// Start serving.
	log.Printf("Serving website on %s", address)
	err = server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
Esempio n. 2
0
func main() {
	Data[1] = "a"
	Data[2] = "b"
	Data[3] = "c"
	Data[4] = "d"
	Data[5] = "e"
	Data[6] = "f"
	Data[7] = "g"
	Data[8] = "h"
	Data[9] = "i"
	Data[10] = "j"

	for _, each := range Instances {
		Cache[g_p(each)] = each
	}

	for k, _ := range Data {
		Cache[g_p(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range Cache {
		S_keys = append(S_keys, k)
	}

	sort.Strings(S_keys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", put_h)
	mux.GET("/keys/:key", h_get)
	server := http.Server{
		Addr:    "0.0.0.0:8187",
		Handler: mux,
	}
	server.ListenAndServe()
}
Esempio n. 3
0
func ExampleSessionMux() {
	sb := NewSrvSessionBuilder("", "/", "example", 60*60*1000, 10000)
	mux := NewSessionMux("/example", sb)
	mux.HFilterFunc("^.*$", func(hs *HTTPSession) HResult {
		log.D("filt 001")
		return HRES_CONTINUE
	})
	//http://localhost:8080/example/ok
	mux.HFunc("^/ok(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.MsgRes("OK")
		return HRES_RETURN
	})
	//http://localhost:8080/example/data
	mux.HFunc("^/data(\\?.*)?$", func(hs *HTTPSession) HResult {
		var tid int64
		var name string
		err := hs.ValidRVal(`
			tid,R|I,R:0
			name,R|S,L:0`, //valid the argument
			&tid, &name)
		if err != nil {
			return hs.MsgResE(1, err.Error())
		}
		return hs.MsgRes(fmt.Sprintf("%v:%v", tid, name))
	})
	mux.HFunc("^/mdata(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.W.Write([]byte("some data\n"))
		return HRES_RETURN
	})
	s := http.Server{Addr: ":8080", Handler: mux}
	err := s.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}
Esempio n. 4
0
File: server.go Progetto: jf/gwp
func main() {
	server := http.Server{
		Addr:    "127.0.0.1:8080",
		Handler: nil,
	}
	server.ListenAndServe()
}
Esempio n. 5
0
func main() {
	Values[1] = "z"
	Values[2] = "y"
	Values[3] = "x"
	Values[4] = "q"
	Values[5] = "w"
	Values[6] = "v"
	Values[7] = "u"
	Values[8] = "t"
	Values[9] = "s"
	Values[10] = "r"

	for _, each := range ListOfServers {
		HashingMapping[calculateHashValue(each)] = each
	}

	for k, _ := range Values {
		HashingMapping[calculateHashValue(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range HashingMapping {
		SortedHashingMappingKeys = append(SortedHashingMappingKeys, k)
	}

	sort.Strings(SortedHashingMappingKeys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", putDataTo)
	mux.GET("/keys/:key", getRequest)
	server := http.Server{
		Addr:    "0.0.0.0:8000",
		Handler: mux,
	}
	server.ListenAndServe()
}
Esempio n. 6
0
func StartServer(server *http.Server) {
	log.Println("Starting server")
	err := server.ListenAndServe()
	if err != nil {
		log.Fatalln("Error: %v", err)
	}
}
Esempio n. 7
0
// Run provides starting of server
func (hs *HttpServer) Run() {
	server := http.Server{
		Addr: hs.Addr,
	}

	go server.ListenAndServe()
}
Esempio n. 8
0
func main() {
	sourceAddress := ":3000"

	ports := []string{
		":3333",
		":3334",
	}
	hostRing := ring.New(len(ports))
	for _, port := range ports {
		url, _ := url.Parse("http://127.0.0.1" + port)
		hostRing.Value = url
		hostRing = hostRing.Next()
	}

	mutex := sync.Mutex{}
	director := func(request *http.Request) {
		mutex.Lock()
		defer mutex.Unlock()
		request.URL.Scheme = "http"
		request.URL.Host = hostRing.Value.(*url.URL).Host
		hostRing = hostRing.Next()
		fmt.Println(hostRing)
	}
	proxy := &httputil.ReverseProxy{Director: director}
	server := http.Server{
		Addr:    sourceAddress,
		Handler: proxy,
	}
	server.ListenAndServe()
}
Esempio n. 9
0
func main() {

	initService()

	var port = flag.String("port", "8000", "please specify the port to start server on")
	flag.Parse()
	logger.Println("Port to start on: " + *port)
	server := http.Server{
		Addr:    ":" + *port,
		Handler: &myHandler{},
	}

	mux = make(map[string]func(http.ResponseWriter, *http.Request))
	mux["/"] = homeHandler
	mux["/healthmetrics"] = healthMetricsHandler
	mux["/addhealthmetrics"] = addHealthMetricsHandler
	mux["/addhealthmetricsform"] = addHealthMetricsFormHandler
	mux["/newuser"] = addUserHandler
	mux["/signupform"] = signupFormHandler
	mux["/login"] = loginHandler
	mux["/loginform"] = loginformHandler
	mux["/logout"] = logoutHandler
	mux["/static"] = staticHandler

	server.ListenAndServe()
}
Esempio n. 10
0
func (h *HTTPServer) Serve(launchdSocket string) error {
	proxy := &httputil.ReverseProxy{
		Director:      h.director,
		Transport:     h.transport,
		FlushInterval: 1 * time.Second,
	}

	serv := http.Server{
		Addr:    h.Address,
		Handler: proxy,
	}

	if launchdSocket == "" {
		return serv.ListenAndServe()
	}

	listeners, err := launch.SocketListeners(launchdSocket)
	if err != nil {
		return err
	}

	var t tomb.Tomb

	for _, l := range listeners {
		t.Go(func() error {
			return serv.Serve(l)
		})
	}

	return t.Wait()
}
Esempio n. 11
0
func main() {
	var httpServer http.Server
	var httpsServer http.Server
	http2.VerboseLogs = true
	http2.ConfigureServer(&httpsServer, nil)

	http.HandleFunc("/auth", authHandler)
	http.HandleFunc("/", handler)
	http.HandleFunc("/js", jsHandler)

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		log.Println("start http listening :18888")
		httpServer.Addr = ":18888"
		log.Println(httpServer.ListenAndServe())
		wg.Done()
	}()
	go func() {
		log.Println("start https listening :18889")
		httpsServer.Addr = ":18889"
		log.Println(httpsServer.ListenAndServeTLS("server.crt", "server.key"))
		wg.Done()
	}()
	wg.Wait()
}
Esempio n. 12
0
File: server.go Progetto: jf/gwp
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/post/", handleRequest)
	server.ListenAndServe()
}
Esempio n. 13
0
func main() {
	var err error
	var f *os.File
	f, err = os.Open("/var/www/index.html")
	if err != nil {
		log.Fatal(err)
	}
	index_bytes, err = ioutil.ReadAll(f)
	if err != nil {
		log.Fatal(err)
	}
	err = f.Close()
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", http_index)
	var srv *http.Server
	srv = &http.Server{
		ReadTimeout: 30 * time.Second,
		Handler:     http.DefaultServeMux,
	}
	go func() {
		var err error
		err = srv.ListenAndServe()
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
	}()
	log.Println("Started")
	select {}
}
Esempio n. 14
0
File: server.go Progetto: jf/gwp
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/hello", log(hello))
	server.ListenAndServe()
}
Esempio n. 15
0
func main() {
	Data[1] = "a"
	Data[2] = "b"
	Data[3] = "c"
	Data[4] = "d"
	Data[5] = "e"
	Data[6] = "f"
	Data[7] = "g"
	Data[8] = "h"
	Data[9] = "i"
	Data[10] = "j"

	for _, each := range ServerArr {
		HashMap[getHash(each)] = each
	}

	for k, _ := range Data {
		HashMap[getHash(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range HashMap {
		SortedHashMapKeys = append(SortedHashMapKeys, k)
	}

	sort.Strings(SortedHashMapKeys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", handlePutRequests)
	mux.GET("/keys/:key", handleGetRequests)
	server := http.Server{
		Addr:    "0.0.0.0:8000",
		Handler: mux,
	}
	server.ListenAndServe()
}
Esempio n. 16
0
// StartServer Starts the OAuth2 token exchange server. Blocks until the server is killed.
func StartServer() {
	clientKeysFile, err := os.Open(clientKeysPath)
	if err != nil {
		log.Fatal(err)
	}

	clientKeysDecoder := json.NewDecoder(clientKeysFile)
	var clientKeys ClientKeys
	if err = clientKeysDecoder.Decode(&clientKeys); err != nil {
		log.Fatal(err)
	}
	log.Println("Client ID:", clientKeys.ClientID)
	log.Println("Client Secret:", clientKeys.ClientSecret)

	userTokensFile, err := os.OpenFile(userTokensPath, os.O_WRONLY, 0666)
	if err != nil {
		log.Fatal(err)
	}
	defer userTokensFile.Close()

	log.Println("Listening")
	http.HandleFunc("/auth/exchange", makeTokenExchangeHandler(clientKeys, userTokensFile))
	server := http.Server{
		Addr:           ":8080",
		Handler:        nil,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Fatal(server.ListenAndServe())
}
Esempio n. 17
0
func (server *Server) start(port int) {
	server.newMyRequests = make(chan *MyRequestToRemote, 100)
	server.doneMyRequests = make(chan *MyRequestToRemote, 100)
	server.activeMyRequests = make(map[string]*MyRequestToRemote)

	server.downloadPercentageQueries = make(chan *DownloadPercentageQuery, 5)

	// ...

	go server.run()

	// as sender
	http.Handle(UrlPrefix_Pull+"/", http.StripPrefix(UrlPrefix_Pull+"/", http.FileServer(http.Dir(FileSavePath))))

	// as receiver
	http.HandleFunc(UrlPrefix_Sync, server.syncHandler)

	// ...
	var address = fmt.Sprintf(":%d", port)

	http_server := http.Server{
		Addr:         address,
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 0,
	}
	log.Printf("Server is listening at %s ...\n", address)
	log.Fatal(http_server.ListenAndServe())
}
Esempio n. 18
0
func main() {
	if _, err := fs.Mount(); err != nil {
		log.Printf("fs-mounting %v\n", err)
		os.Exit(-1)
	}

	var server http.Server
	server.Addr = envGetOrAlternatives(EnvCachyServerAddress, ":8080")

	log.Printf("cachy server running on %q\n", server.Addr)

	http.HandleFunc("/", Cache)
	http.HandleFunc("/cache", Cache)

	certFilepath := envGetOrAlternatives(EnvCachyCertFile, "cachy.cert")
	keyFilepath := envGetOrAlternatives(EnvCachyKeyFile, "cachy.key")

	if envGetOrAlternatives("http1") != "" {
		if err := server.ListenAndServe(); err != nil {
			log.Printf("serving http: %v\n", err)
		}
	} else {
		if err := server.ListenAndServeTLS(certFilepath, keyFilepath); err != nil {
			log.Printf("servingTLS: %v\n", err)
		}
	}
}
Esempio n. 19
0
File: server.go Progetto: jf/gwp
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/body", body)
	server.ListenAndServe()
}
Esempio n. 20
0
func main() {
	mux := httprouter.New()

	//create file on set up only if doesnt exist
	//LOG_FILE_NAME
	if _, err := os.Stat(LOG_FILE_NAME); os.IsNotExist(err) {
		// path/to/whatever does not exist
		fmt.Println("log file does not exist,creating the file")
		f, err := os.OpenFile(LOG_FILE_NAME, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			fmt.Printf(err.Error())
		}
		defer f.Close()
	}

	writeToAFile("Response")

	mux.GET("/keys", GetBulkData)

	server := http.Server{
		Addr:    "0.0.0.0:3006",
		Handler: mux,
	}

	server.ListenAndServe()
}
Esempio n. 21
0
func main() {
	flag.Parse()
	portOffset := *gostrich.PortOffset
	newBinding := gostrich.UpdatePort(*binding, portOffset)

	conf := rpcx.ReliableServiceConf{
		Name:        "tweetbutton",
		Makers:      makeAll(*cassandras, *cassandraTimeout),
		Retries:     *retries,
		Concurrency: *concurrency,
		Stats:       gostrich.AdminServer().GetStats().Scoped("tbapi"),
		Prober:      rpcx.ProberReqLastFail,
	}
	cas := rpcx.NewReliableService(conf)

	state := ServerState{cas}

	server := http.Server{
		newBinding,
		&state,
		*readTimeout,
		*writeTimeout,
		0,
		nil,
	}
	logger.LogInfo("Tweetbutton starting up...\n")
	go func() {
		logger.LogInfo(server.ListenAndServe())
	}()

	gostrich.StartToLive(nil)
}
Esempio n. 22
0
func main() {

	flags := getCmdLineArgs()
	fmt.Println("Command Line Flags:")
	if flags.isProxy {
		fmt.Println("[isProxy: true]")
	} else {
		fmt.Println("[isProxy: false]")
	}
	fmt.Println("[listenUrl: " + flags.listenIP + "]")
	fmt.Println("[listenPort: " + flags.listenPort + "]")
	fmt.Println("[proxyUrl: " + flags.proxyIP + "]")
	fmt.Println("[proxyPort: " + flags.proxyPort + "]\n")

	server := http.Server{
		Addr:    flags.listenIP + ":" + flags.listenPort,
		Handler: &myHandler{},
	}

	setupRoutes()

	fmt.Println("Listening to " + server.Addr)
	if !flags.isProxy {
		go startHeartbeat(5, flags)
	}
	server.ListenAndServe()
}
Esempio n. 23
0
// Serve starts the server (http.DefaultServeMux) on given port, loops forever.
func (s *ProxyServer) Serve(port int) error {
	server := http.Server{
		Addr:    fmt.Sprintf(":%d", port),
		Handler: s.mux,
	}
	return server.ListenAndServe()
}
func startHttpServers(c *C) []int {
	// start an http server that responds with the port # it's listening on
	startHttpServer := func(port int) {
		serveMux := http.NewServeMux()
		serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprintf(w, "%d", port)
		})
		server := http.Server{
			Addr:    fmt.Sprintf("%s:%d", "127.0.0.1", port),
			Handler: serveMux,
		}
		server.ListenAndServe()
	}

	ports := []int{
		test_utils.RandomListenPort(c),
		test_utils.RandomListenPort(c),
		test_utils.RandomListenPort(c),
		test_utils.RandomListenPort(c),
		test_utils.RandomListenPort(c)}

	for _, port := range ports {
		go startHttpServer(port)
	}
	for _, port := range ports {
		test_utils.EnsureListen(c, fmt.Sprintf("127.0.0.1:%d", port))
	}

	return ports
}
Esempio n. 25
0
func main() {
	server := http.Server{
		Addr:    ":8080",
		Handler: &myHandler{},
	}
	server.ListenAndServe()
}
Esempio n. 26
0
func main() {
	nodes = []string{"3000", "3001", "3002"}
	numberofReplicas = 100
	for _, node := range nodes {
		addNodesOnCircle(node)
	}
	sort.Sort(sortedCircle)
	data = map[int]string{1: "a", 2: "b", 3: "c", 4: "d", 5: "e",
		6: "f", 7: "g", 8: "h", 9: "i", 10: "j"}
	for key, value := range data {
		var objData Data
		objData.Key = key
		objData.Value = value
		JsonData, _ := m.Marshal(objData)
		nodeNumber := getNode(key)
		fmt.Print("Node Number: ")
		fmt.Println(nodeNumber)
		fmt.Print("key value: ")
		fmt.Println(key)
		url := "http://localhost:" + nodeNumber + "/keys"
		http.Post(url, "application/json", bytes.NewBuffer(JsonData))
	}
	mux := httprouter.New()
	mux.GET("/keys/:key_id", findKeys)
	mux.GET("/keys", findAllKeys)
	mux.PUT("/keys/:key_id/:value", updateKey)
	server := http.Server{
		Addr:    ":8080",
		Handler: mux,
	}
	server.ListenAndServe()
}
Esempio n. 27
0
File: server.go Progetto: jf/gwp
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/process", process)
	server.ListenAndServe()
}
Esempio n. 28
0
//Main Function
func main() {
	fmt.Println("Starting the client")
	MyRESTServers = []string{"127.0.0.1:3000",
		"127.0.0.1:3001",
		"127.0.0.1:3002"}

	Ring = consistentHashing.New(MyRESTServers)

	mux := httprouter.New()

	//handler to service GET ALL request
	mux.GET("/keys", GetAllKeys)

	//handler to service GET request
	mux.GET("/keys/:id", GetKey)

	//handler to service PUT request
	mux.PUT("/keys/:id/:value", PutKey)

	server := http.Server{
		Addr:    "0.0.0.0:8080",
		Handler: mux,
	}
	server.ListenAndServe()
}
Esempio n. 29
0
func Run() {
	var r *int = flag.Int("r", 0, "read timeout")
	var w *int = flag.Int("w", 0, "write timeout")

	port := CFG.Int("port")

	if port == 0 {
		port = 80
	}

	host := CFG.Str("host")
	if host == "" {
		host = "127.0.0.1"
	}

	address := fmt.Sprintf("%s:%d", host, port)
	LOGGER.Log("WebGO running", address)

	server := http.Server{
		Addr:         address,
		ReadTimeout:  time.Duration(*r) * time.Second,
		WriteTimeout: time.Duration(*w) * time.Second,
		Handler:      &app,
	}

	//server.SetKeepAlivesEnabled(false)

	err := server.ListenAndServe()
	if err != nil {
		LOGGER.Fatal(err)
	}

}
Esempio n. 30
0
func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	useful.LogFile.Init()

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		io.WriteString(w, "Hello, world!")
	})

	myHandler := useful.NewUsefulHandler(handler)

	http.Handle("/", myHandler)
	server := http.Server{
		Addr:    ":1234",
		Handler: nil,
	}
	server.ListenAndServe()
}