예제 #1
1
파일: main.go 프로젝트: highway900/sigh
func main() {
	flag.Parse()
	if flag.NArg() != 1 {
		log.Fatal("filename not specified")
	}
	filename := flag.Args()[0]

	h := &handler{
		filename: filename,
		c:        make(chan bool),
	}

	// Watch file(s) for changes and trigger refresh
	go h.watcher(h.filename)

	http.HandleFunc("/ws/echo", h.reloadHandler)
	http.Handle("/", h)
	go http.ListenAndServe(":3000", nil)
	err := http.ListenAndServe(":3000", nil)
	if err != nil {
		panic("Error: " + err.Error())
	}

	fmt.Println("Done")
}
예제 #2
1
func main() {
	flag.Parse()

	if arguments.pprof {
		log.Println("pprof enabled")
		go func() {
			log.Println(http.ListenAndServe("localhost:6060", nil))
		}()

		fp, err := os.Create("backend.pprof")
		if err != nil {
			panic(err)
		}
		defer fp.Close()

		pprof.StartCPUProfile(fp)
		defer pprof.StopCPUProfile()
	}

	if err := loadTree(arguments.tree); err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	http.Handle("/", http.FileServer(http.Dir(arguments.web)))
	http.Handle("/render", websocket.Handler(renderServer))

	log.Println("waiting for connections...")
	if err := http.ListenAndServe(fmt.Sprintf(":%v", arguments.port), nil); err != nil {
		log.Println(err)
		os.Exit(-1)
	}
}
예제 #3
1
파일: web.go 프로젝트: jnb666/gogp
// ListenAndServe method serve plots via http on port. HTML docs should be under the webRoot directory.
// This routine won't return so kick off any other processes as a goroutine.
func (l *Logger) ListenAndServe(port, webRoot string) {
	var err error
	if l.step != nil {
		http.HandleFunc("/step", func(w http.ResponseWriter, r *http.Request) {
			sendJSON(w, r, <-l.step)
		})
		http.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
			l.start <- empty{}
		})
	}
	http.HandleFunc("/stats/", l.statsHandler(len("/stats/")))
	http.HandleFunc("/plot/List", func(w http.ResponseWriter, r *http.Request) {
		sendJSON(w, r, l.options)
	})
	http.HandleFunc("/plot/Plot", func(w http.ResponseWriter, r *http.Request) {
		sendJSON(w, r, l.plots)
	})
	http.HandleFunc("/plot/SVGPlot", func(w http.ResponseWriter, r *http.Request) {
		send(w, r, l.svgplot, "image/svg+xml")
	})
	http.HandleFunc("/plot/Hist", l.histogramPlotHandler())
	http.HandleFunc("/plot/", l.statsPlotHandler(len("/plot/")))
	http.HandleFunc("/graph", l.graphHandler())
	http.Handle("/", http.FileServer(http.Dir(webRoot)))
	log.Println("starting web server on", port)
	if Debug {
		err = http.ListenAndServe(port, logRequests(http.DefaultServeMux))
	} else {
		err = http.ListenAndServe(port, nil)
	}
	log.Fatal(err)
}
예제 #4
1
파일: main.go 프로젝트: gunjan5/Skywalker
func main() {
	router := mux.NewRouter()

	ctx := context.Background()
	svc := yell.YellingService{}

	yellHandler := httptransport.NewServer(
		ctx,
		yell.MakeYellEndpoint(svc),
		yell.DecodeYellRequest,
		yell.EncodeResponse,
	)

	composeHandler := httptransport.NewServer(
		ctx,
		compose.MakeComposeEndpoint(svc),
		compose.DecodeComposeRequest,
		compose.EncodeResponse,
	)

	router.HandleFunc("/", RootHandler)
	router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(*staticPath))))
	http.Handle("/yell", yellHandler)
	http.Handle("/compose", composeHandler)
	go http.ListenAndServe(":8080", nil)
	go log.Fatal(http.ListenAndServe(":8081", router))
}
예제 #5
1
func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	if len(os.Args) > 1 && os.Args[1] == "web" {
		handler := func(w http.ResponseWriter, r *http.Request) {
			r.ParseForm()
			for k, v := range r.Form {
				if k == "height" {
					height, _ = strconv.Atoi(strings.Join(v, ""))
				} else if k == "width" {
					width, _ = strconv.Atoi(strings.Join(v, ""))
				} else if k == "color" {
					color = v[0]
				}
			}
			w.Header().Set("Content-Type", "image/svg+xml")
			drawSVG(w, r)
		}
		http.HandleFunc("/", handler)
		//!-http
		log.Fatal(http.ListenAndServe("localhost:8000", nil))
		return
	}
	http.HandleFunc("/draw", drawSVG)
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
예제 #6
1
func main() {

	location2 = 0
	location3 = 0
	location1 = 0

	mutliplexer := httprouter.New()

	mutliplexer.GET("/keys", PingRedisPorts)

	mutliplexer.GET("/keys/:key_id", GetOneKey)

	mutliplexer.PUT("/keys/:key_id/:value", AddKeyValues)

	mutliplexer.GET("/all", AllRedisKeyValues)

	mutliplexer.GET("/mapping", GetMapping)

	go http.ListenAndServe(":3000", mutliplexer)

	go http.ListenAndServe(":3001", mutliplexer)

	go http.ListenAndServe(":3002", mutliplexer)

	select {}
}
예제 #7
0
func main() {
	dataDirectory := flag.String("d", defaultDataDirectory, "Directory where dictionary files are located")
	serviceListenPort := flag.Int("p", defaultServiceListenPort, "Service Listen Port")
	adminListenPort := flag.Int("a", defaultAdminListenPort, "Admin Listen Port")
	allowedOrigin := flag.String("c", handlers.AllowedOrigin, "CORS Allowed Origin")
	flag.Parse()

	log.Printf("Using data directory %s", *dataDirectory)
	handlers.DataDirectory = *dataDirectory
	handlers.LoadDictionaries()

	r := mux.NewRouter()
	r.HandleFunc("/twocents", handlers.MetaVersionsHandler).Methods("GET")
	r.HandleFunc("/twocents/{version:v1}", handlers.MetaDictionariesHandler).Methods("GET")
	r.HandleFunc("/twocents/{version:v1}/{dictionary}/{query}", handlers.TwoCentsHandlerV1).Methods("GET")
	r.HandleFunc("/twocents/{version:v1}/{dictionary}/{query}/{limit:[0-9]+}", handlers.TwoCentsHandlerV1).Methods("GET")
	r.HandleFunc("/twocents/{version:v1}/{dictionary}/{query}/{limit:[0-9]+}/{filter}", handlers.TwoCentsHandlerV1).Methods("GET")
	http.Handle("/", r)
	log.Printf("Service listening on port %d", *serviceListenPort)
	go func() {
		log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *serviceListenPort), nil))
	}()
	log.Printf("Admin listening on port %d", *adminListenPort)
	if *allowedOrigin != "" {
		log.Printf("Setting CORS Origin to %s", *allowedOrigin)
		handlers.AllowedOrigin = *allowedOrigin
	}

	//TODO: Find a better way to pass a different router to the admin server
	http.ListenAndServe(fmt.Sprintf(":%d", *adminListenPort), &adminHandler{})
}
예제 #8
0
파일: main.go 프로젝트: bentranter/lazyblog
func main() {
	if len(os.Args) > 1 {
		switch os.Args[1] {
		case "setup":
			defer lazyblog.DefaultStore.Close()
			lazyblog.Setup()
		case "start":
			defer lazyblog.DefaultStore.Close()
			numUsers, err := lazyblog.NumUsers()
			if err != nil {
				panic(err)
			}
			if numUsers < 1 {
				log.Fatalln("Please run setup before running start")
				return
			}

			if os.Getenv("LAZYBLOG_ENV") == "dev" {
				log.Fatalln(http.ListenAndServe(":3000", lazyblog.Router))
			}
			log.Fatalln(http.ListenAndServe(":80", lazyblog.Router))
		default:
			fmt.Println(usage)
		}
	} else {
		fmt.Println(usage)
	}
}
예제 #9
0
파일: main.go 프로젝트: arvinkulagin/beeper
func main() {
	logger := log.NewLogger()
	cfg := config.Default()
	flag.StringVar(&cfg.WSAddress, "ws", cfg.WSAddress, "Websocket address")
	flag.StringVar(&cfg.RESTAddress, "rest", cfg.RESTAddress, "REST address")
	flag.StringVar(&cfg.Origin, "o", cfg.Origin, "Origin URL")
	file := flag.String("config", "", "Config file")
	flag.Parse()
	if *file != "" {
		err := config.FromFile(*file, &cfg)
		if err != nil {
			logger.Err.Fatal(err)
		}
		flag.Parse()
	}
	broker := pubsub.NewBroker()
	go func() {
		wsRouter := mux.NewRouter()
		wsRouter.Handle("/{id}", handlers.WSHandler{Broker: broker, Config: cfg, Logger: logger})
		logger.Out.Println("Listening websockets on", cfg.WSAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.WSAddress, wsRouter))
	}()
	go func() {
		restRouter := mux.NewRouter()
		restRouter.Handle("/topic", handlers.List{Broker: broker, Logger: logger}).Methods("GET")
		restRouter.Handle("/topic", handlers.Add{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Pub{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Del{Broker: broker, Logger: logger}).Methods("DELETE")
		restRouter.Handle("/ping", handlers.Ping{Logger: logger}).Methods("GET")
		logger.Out.Println("Listening REST on", cfg.RESTAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.RESTAddress, restRouter))
	}()
	wait := make(chan struct{})
	<-wait
}
예제 #10
0
func main() {
	f := flag.String("config", "$HOME/.config/mallory.json", "config file")
	flag.Parse()

	L.Printf("Starting...\n")
	c, err := m.NewConfig(*f)
	if err != nil {
		L.Fatalln(err)
	}

	L.Printf("Connecting remote SSH server: %s\n", c.File.RemoteServer)
	smart, err := m.NewServer(m.SmartSrv, c)
	if err != nil {
		L.Fatalln(err)
	}
	normal, err := m.NewServer(m.NormalSrv, c)
	if err != nil {
		L.Fatalln(err)
	}

	go func() {
		L.Printf("Local normal HTTP proxy: %s\n", c.File.LocalNormalServer)
		L.Fatalln(http.ListenAndServe(c.File.LocalNormalServer, normal))
	}()

	L.Printf("Local smart HTTP proxy: %s\n", c.File.LocalSmartServer)
	L.Fatalln(http.ListenAndServe(c.File.LocalSmartServer, smart))
}
예제 #11
0
func main() {
	port := flag.Int("port", 6969, "port to serve websockets on")
	cport := flag.Int("cport", 6868, "port to listen for control messages on")
	nCpu := flag.Int("ncpu", runtime.NumCPU(), "number of cpus to use, defaults to number of processors available")
	mgrVerbose := flag.Bool("verbose-merry-go-round", false, "Verbose output from merry-go-round carousels")

	flag.Parse()

	runtime.GOMAXPROCS(*nCpu)
	mgr.VERBOSE = *mgrVerbose

	ss := socketserver.NewSocketServer()

	go func() {
		bindAddr := fmt.Sprintf(":%d", *port)
		fmt.Printf("SocketServer going up at: %s\n", bindAddr)
		log.Fatal(http.ListenAndServe(bindAddr, ss))
	}()

	sc := control.NewSocketController(ss)

	bindAddr := fmt.Sprintf(":%d", *cport)
	fmt.Printf("SocketController going up at: %s\n", bindAddr)
	log.Fatal(http.ListenAndServe(bindAddr, sc))
}
예제 #12
0
func main() {
	flag.Parse()
	if *uberClientId == "" || *uberClientSecret == "" || *httpsUrl == "" || *httpUrl == "" || *googleMapsApiKey == "" {
		flag.PrintDefaults()
		return
	}
	uberApiClient = &UberApiClient{
		url:          *uberApiHost,
		clientSecret: *uberClientSecret,
		clientId:     *uberClientId,
	}

	mondoApiClient = &MondoApiClient{url: *mondoApiUrl}

	router.HandleFunc("/", indexGet).Methods("GET").Name(Index)
	router.HandleFunc("/login", loginPost).Methods("POST").Name(Login)
	router.HandleFunc("/logout", logoutPost).Methods("POST").Name(Logout)
	router.HandleFunc("/uber/setauthcode", uberSetAuthCodeGet).Methods("GET").Name(SetAuthCode)
	router.HandleFunc("/mondo/webhook/{sessionId}", mondoWebhookPost).Methods("POST").Name(MondoWebhook)
	router.PathPrefix("/").Handler(http.FileServer(http.Dir("./")))

	go func() {
		log.Printf("Listening on %s\n", *httpAddr)
		log.Fatal(http.ListenAndServe(*httpAddr, middleware(router)))
	}()

	log.Printf("Listening on %s\n", *httpsAddr)
	if strings.Contains(*httpsAddr, "443") {
		log.Fatal(http.ListenAndServeTLS(*httpsAddr, *certFile, *keyFile, middleware(router)))
	} else {
		log.Fatal(http.ListenAndServe(*httpsAddr, middleware(router)))
	}
}
예제 #13
0
파일: main.go 프로젝트: mukta3396/abalone
func main() {
	flag.Parse()
	r := mux.NewRouter()
	operatorPost := make(chan []byte)
	clientPost := make(chan []byte)
	clientGet := make(chan []byte)
	gameToOperator := make(chan []byte)
	r.Path("/frontend").Methods("GET").HandlerFunc(handleClientGet(clientGet))
	r.Path("/frontend").Methods("POST").HandlerFunc(handleClientPost(clientPost))
	r.Path("/move").Methods("POST").HandlerFunc(handleOperatorPost(operatorPost, gameToOperator))
	go func() {
		var previousGame []byte
		for {
			sendGameToClient := clientGet
			if previousGame == nil {
				sendGameToClient = nil
			}
			select {
			case x := <-clientPost:
				gameToOperator <- x
				previousGame = nil

			case x := <-operatorPost:
				previousGame = x

			case sendGameToClient <- previousGame:
			}
		}
	}()

	go func() {
		http.ListenAndServe(":"+*port, r)
	}()
	http.ListenAndServe(":1337", r)
}
예제 #14
0
func main() {
	// Setup the global variables and settings
	err := models.Setup()
	if err != nil {
		fmt.Println(err)
	}
	wg := &sync.WaitGroup{}
	wg.Add(1)
	// Start the web servers
	go func() {
		defer wg.Done()
		if config.Conf.AdminConf.UseTLS { // use TLS for Admin web server if available
			Logger.Printf("Starting admin server at https://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.AdminConf.ListenURL, config.Conf.AdminConf.CertPath, config.Conf.AdminConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		} else {
			Logger.Printf("Starting admin server at http://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.AdminConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		}
	}()
	wg.Add(1)
	go func() {
		defer wg.Done()
		if config.Conf.PhishConf.UseTLS { // use TLS for Phish web server if available
			Logger.Printf("Starting phishing server at https://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.PhishConf.ListenURL, config.Conf.PhishConf.CertPath, config.Conf.PhishConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		} else {
			Logger.Printf("Starting phishing server at http://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.PhishConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		}
	}()
	wg.Wait()
}
예제 #15
0
func main() {

	db, err := bolt.Open("proxy.db", 0600, nil)

	if err != nil {
		log.Fatal("Fatal: %s\n", err.Error())
	}

	defer db.Close()

	adminServer := proxyAdminServer{db}

	adminMux := bone.New()
	adminMux.Get("/proxy", http.HandlerFunc(adminServer.GetProxies))
	adminMux.Delete("/proxy/:id", http.HandlerFunc(adminServer.DeleteProxyIteraction))
	adminMux.Post("/proxy", http.HandlerFunc(adminServer.NewProxyIteraction))

	proxyServer := proxyServer{&http.Client{}, db}

	mux := bone.New()

	mux.Handle("/*", http.HandlerFunc(proxyServer.ProxyHandler))

	go func(port string) {
		log.Println("Starting admin server")
		log.Fatal(http.ListenAndServe(port, adminMux))
	}(":9080")
	log.Println("Starting test proxy")
	log.Fatal(http.ListenAndServe(":9090", mux))
}
예제 #16
0
파일: main.go 프로젝트: qmdx/mygo
func main() {
	flag.Parse()

	peers := gc.NewHTTPPool("http://localhost:" + *port)
	peers.Set("http://localhost:8001", "http://localhost:8002")

	cg = gc.NewGroup("QRCache", 1<<20, gc.GetterFunc(
		func(ctx gc.Context, key string, dest gc.Sink) error {
			fmt.Printf("asking for data of %s\n", key)
			url := fmt.Sprintf("http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl=%s", key)
			resp, err := http.Get(url)
			if err != nil {
				return nil
			}
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				return nil
			}
			value := base64.StdEncoding.EncodeToString(body)
			dest.SetBytes([]byte(value))
			return nil
		}))

	// run groupcache process in goroutine
	go http.ListenAndServe("localhost:"+*port, peers)

	http.Handle("/", http.HandlerFunc(QR))
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
예제 #17
0
func main() {
	// Use all available cores
	runtime.GOMAXPROCS(runtime.NumCPU())

	flag.Parse()

	rout := NewRouter(*mongoUrl, *mongoDbName)
	rout.ReloadRoutes()

	log.Println("router: listening for requests on " + *pubAddr)
	log.Println("router: listening for refresh on " + *apiAddr)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.NotFound(w, r)
			return
		}

		rout.ReloadRoutes()
	})

	go http.ListenAndServe(*pubAddr, rout)
	go http.ListenAndServe(*apiAddr, nil)

	<-quit
}
예제 #18
0
파일: proxy.go 프로젝트: qrtz/livedev
func (p *proxy) ListenAndServe() error {
	addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort("", strconv.Itoa(p.port)))
	if err != nil {
		return err
	}

	p.addr = addr
	done := make(chan error, 1)
	go func() {
		done <- http.ListenAndServe(p.addr.String(), p)
	}()

	select {
	case err := <-done:
		done <- err
	default:
		if addr, err := findAvailablePort(); err == nil {
			go func(port int) {
				p.codeViewerMux.Port = port
				p.codeViewerMux.Addr = net.JoinHostPort("", strconv.Itoa(port))
				done <- http.ListenAndServe(p.codeViewerMux.Addr, p.codeViewerMux.Handler)
			}(addr.Port)
		} else {
			done <- err
		}
	}

	err = <-done

	p.shutdown()
	return err
}
예제 #19
0
func main() {
	go func() {
		fmt.Println(http.ListenAndServe("localhost:9002", nil))
	}()
	host := "localhost:9001"
	fmt.Println("starting server " + host + "..")

	routing.RouteDirectory("assets")

	routing.Route("/", actions.Root)
	routing.Route("/login/", actions.Login)
	routing.Route("/logout/", actions.Logout)
	routing.Route("/api/{entity}/", actions.Api)
	routing.Route("/{category}/", actions.Category)
	routing.Route("/{category}/{post_url}/", actions.Post)

	routing.RouteFile("/sitemap.xml", "public/sitemap.xml")
	routing.RouteFile("/robots.txt", "public/robots.txt")

	err := http.ListenAndServe(host, routing.Router())
	if err != nil {
		fmt.Println("Error serving " + host)
		fmt.Println(err)
	}
}
예제 #20
0
파일: fogo.go 프로젝트: kendellfab/fogo
// Binds and runs the application on the given config port.
func (f *Fogo) Run() {
	f.router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(f.config.AssetDirectory))))
	if f.config.CatchAll {
		f.router.PathPrefix("/").Handler(http.FileServer(http.Dir(f.config.AssetDirectory)))
	}
	port := f.config.Port

	if f.config.PortIncrement {
		for {
			err := http.ListenAndServe(f.config.GetConnectionString(), f.router)
			if err != nil {
				if strings.Contains(err.Error(), BIND_ERR) {
					port++
					time.Sleep(100 * time.Millisecond)
				} else {
					f.logger.LogError(err)
					os.Exit(2)
				}
			}
		}
	} else {
		if err := http.ListenAndServe(f.config.GetConnectionString(), f.router); err != nil {
			f.logger.LogError(err)
		}

	}

}
예제 #21
0
파일: main.go 프로젝트: polyzz/mallory
func serve() {
	L.Printf("Starting...\n")
	L.Printf("PID: %d\n", os.Getpid())

	c, err := NewConfig(*FConfig)
	if err != nil {
		L.Fatalln(err)
	}

	L.Printf("Connecting remote SSH server: %s\n", c.File.RemoteServer)

	wait := make(chan int)
	go func() {
		normal, err := NewServer(NormalSrv, c)
		if err != nil {
			L.Fatalln(err)
		}
		L.Printf("Local normal HTTP proxy: %s\n", c.File.LocalNormalServer)
		L.Fatalln(http.ListenAndServe(c.File.LocalNormalServer, normal))
		wait <- 1
	}()

	go func() {
		smart, err := NewServer(SmartSrv, c)
		if err != nil {
			L.Fatalln(err)
		}
		L.Printf("Local smart HTTP proxy: %s\n", c.File.LocalSmartServer)
		L.Fatalln(http.ListenAndServe(c.File.LocalSmartServer, smart))
		wait <- 1
	}()
	<-wait
}
예제 #22
0
// Run the HTTP handler, which exposes an HTTP interface to control tasks
func (handler *HTTPHandler) Run() {
	if handler.Logger == nil {
		handler.Logger = log.New(os.Stdout, "[HTTPHandler] ", log.Ldate|log.Ltime)
	}
	m := martini.Classic()
	http.ListenAndServe(handler.Host+":"+string(handler.Port), m)

	// routing
	m.Get("/tasks", handler.taskStatus)
	m.Get("/tasks/:id", handler.taskStatus)

	m.Get("/list", handler.taskList)

	m.Get("/tasks/:id/start", handler.taskStart)
	m.Put("/tasks/:id/start", handler.taskStart)
	m.Post("/tasks/:id/start", handler.taskStart)

	m.Get("/tasks/:id/list", handler.taskListWorkers)

	m.Delete("/tasks", handler.taskStop)
	m.Delete("/tasks/:id", handler.taskStop)
	m.Put("/tasks/:id/stop", handler.taskStop)
	m.Post("/tasks/:id/stop", handler.taskStop)

	m.Get("/tasks/:id/set/:name/:value", handler.taskSetOption)
	m.Post("/tasks/:id/set/:name/:value", handler.taskSetOption)
	m.Put("/tasks/:id/set/:name/:value", handler.taskSetOption)

	//m.Run()

	address := fmt.Sprintf(":%d", handler.Port)
	handler.Logger.Println("HTTP handler listening on", address)

	handler.Logger.Fatalln(http.ListenAndServe(address, m))
}
예제 #23
0
파일: app.go 프로젝트: zqzca/back
// Run the application, start http and scp server.
func Run(appConfig Config) {
	config = appConfig

	// Connect to DB
	db, err := lib.Connect()
	if err != nil {
		fmt.Printf("Failed to connect to db")
		return
	}

	// Logging
	log := logrus.New()
	log.Level = logrus.DebugLevel
	log.Out = os.Stdout
	log.Formatter = &logrus.TextFormatter{}

	// Websockets
	ws := ws.NewServer()

	// Shared dependencies between all controller
	deps := dependencies.Dependencies{
		Fs:     afero.NewOsFs(),
		Logger: log,
		DB:     db,
		WS:     ws,
	}

	ws.Dependencies = &deps
	go ws.Start()

	// // Start SCP
	// scp := scp.Server{}
	// scp.DB = deps.DB
	// scp.Logger = deps.Logger
	// scp.CertPath = "certs/scp.rsa"
	// scp.BindAddr = config.SCPBindAddr
	// go scp.ListenAndServe()

	if config.Secure {
		c := autocert.DirCache("certs")
		m := autocert.Manager{
			Cache:      c,
			Prompt:     autocert.AcceptTOS,
			HostPolicy: autocert.HostWhitelist("x.zqz.ca"),
		}

		s := &http.Server{
			Addr:      config.HTTPBindAddr,
			TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
		}

		deps.Info("Listening for HTTP1.1 Connections", "addr", ":3001")
		deps.Info("Listening for HTTP2 Connections", "addr", config.HTTPBindAddr)
		go http.ListenAndServe(":3001", secureRedirect())
		s.ListenAndServeTLS("", "")
	} else {
		deps.Info("Listening for HTTP1.1 Connections", "addr", config.HTTPBindAddr)
		http.ListenAndServe(config.HTTPBindAddr, Routes(deps))
	}
}
예제 #24
0
파일: main.go 프로젝트: itscaro/go-workers
func main() {
	// Parse the command-line flags.
	flag.Parse()

	// Start the dispatcher.
	fmt.Println("Starting the dispatcher")
	dispatcherWork = workers.Dispatcher{}
	dispatcherWork.Start(*NWorkers, workerWorkHandler)

	dispatcherHello = workers.Dispatcher{}
	dispatcherHello.Start(*NWorkers, workerHelloHandler)

	// Register our collector as an HTTP handler function.
	log.Println("Registering the hanlders")
	http.HandleFunc("/work", hanlderWork)
	http.HandleFunc("/hello", hanlderHello)

	// Start the HTTP server!
	log.Println("HTTP server listening on", *HTTPAddr)
	if err := http.ListenAndServe(*HTTPAddr, nil); err != nil {
		fmt.Println(err.Error())
	}

	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()
}
예제 #25
0
// Starts and runs the server given its configuration. (This function never returns.)
func RunServer(config *ServerConfig) {
	PrettyPrint = config.Pretty

	if os.Getenv("GOMAXPROCS") == "" && runtime.GOMAXPROCS(0) == 1 {
		cpus := runtime.NumCPU()
		if cpus > 1 {
			runtime.GOMAXPROCS(cpus)
			base.Log("Configured Go to use all %d CPUs; setenv GOMAXPROCS to override this", cpus)
		}
	}

	sc := NewServerContext(config)
	for _, dbConfig := range config.Databases {
		if err := sc.AddDatabaseFromConfig(dbConfig); err != nil {
			base.LogFatal("Error opening database: %v", err)
		}
	}

	base.Log("Starting admin server on %s", *config.AdminInterface)
	go func() {
		if err := http.ListenAndServe(*config.AdminInterface, CreateAdminHandler(sc)); err != nil {
			base.LogFatal("HTTP server failed: %v", err)
		}
	}()

	base.Log("Starting server on %s ...", *config.Interface)
	if err := http.ListenAndServe(*config.Interface, CreatePublicHandler(sc)); err != nil {
		base.LogFatal("HTTP server failed: %v", err)
	}
}
예제 #26
0
파일: odot.go 프로젝트: Ottermad/odotgo
func main() {
	db := NewDB()
	r := httprouter.New()

	r.ServeFiles("/static/*filepath", http.Dir("public"))

	r.GET("/", todo.TodoListListing(db))
	r.GET("/todo", todo.TodoListListing(db))

	r.GET("/todo/add", todo.AddTodoListGet(db))
	r.POST("/todo/add", todo.AddTodoListPost(db))

	r.GET("/todo/view/:id", todo.TodoListDetail(db))

	r.GET("/todo/edit/:id", todo.EditTodoListGet(db))
	r.POST("/todo/edit/:id", todo.EditTodoListPost(db))

	r.GET("/todo/add-item/:id", todo.AddTodoListItemGet(db))
	r.POST("/todo/add-item/:id", todo.AddTodoListItemPost(db))

	r.GET("/todo/delete/:id", todo.DeleteTodoList(db))

	r.GET("/todo/delete-item/:todolistid/:todoitemid", todo.DeleteTodoListItem(db))

	if os.Getenv("LOCAL_DEV") == "TRUE" {
		http.ListenAndServe(":8080", r)
	} else {
		http.ListenAndServe(":"+os.Getenv("PORT"), r)
	}

}
예제 #27
0
func ListenAndServe(addr string, handler http.Handler) error {
	if handler == nil {
		return http.ListenAndServe(addr, DefauleRouter)
	}

	return http.ListenAndServe(addr, handler)
}
예제 #28
0
파일: main.go 프로젝트: kyeongdong/3
func main() {
	flag.Parse()

	IPs = parseIPs()
	MinPort, MaxPort = parsePorts()

	thisAddr = canonicalAddr(*flag_addr, IPs)
	var err error
	thisHost, _, err = net.SplitHostPort(thisAddr)
	util.FatalErr(err)
	DetectMumax()
	DetectGPUs()
	LoadJobs()

	http.HandleFunc("/do/", HandleRPC)
	http.HandleFunc("/", HandleStatus)
	httpfs.RegisterHandlers()

	// Listen and serve on all interfaces
	go func() {
		log.Println("serving at", thisAddr)

		// try to listen and serve on all interfaces other than thisAddr
		// this is for convenience, errors are not fatal.
		_, p, err := net.SplitHostPort(thisAddr)
		Fatal(err)
		ips := util.InterfaceAddrs()
		for _, ip := range ips {
			addr := net.JoinHostPort(ip, p)
			if addr != thisAddr { // skip thisAddr, will start later and is fatal on error
				go func() {
					err := http.ListenAndServe(addr, nil)
					if err != nil {
						log.Println("info:", err, "(but still serving other interfaces)")
					}
				}()
			}
		}

		// only on thisAddr, this server's unique address,
		// we HAVE to be listening.
		Fatal(http.ListenAndServe(thisAddr, nil))
	}()

	ProbePeer(thisAddr) // make sure we have ourself as peer
	go FindPeers(IPs, MinPort, MaxPort)
	go RunComputeService()
	go LoopWatchdog()
	go RunShareDecay()

	// re-load jobs every hour so we don't stall on very exceptional circumstances
	go func() {
		for {
			time.Sleep(1 * time.Hour)
			LoadJobs()
		}
	}()

	<-make(chan struct{}) // wait forever
}
예제 #29
0
func Run() {
	// 开启最大核心数运行
	runtime.GOMAXPROCS(runtime.NumCPU())

	// 预绑定路由
	Router()
	// 开启websocket
	go func() {
		reporter.Println("[pholcus] websocket server Running on ", wsAddr)
		if err := http.ListenAndServe(wsAddr, nil); err != nil {
			reporter.Fatal("Websocket ListenAndServe: ", err)
		}
	}()
	// 开启websocket log
	go func() {
		reporter.Println("[pholcus] websocket log server Running on ", wslogAddr)
		if err := http.ListenAndServe(wslogAddr, nil); err != nil {
			reporter.Fatal("Websocket Log ListenAndServe: ", err)
		}
	}()
	// 开启http
	reporter.Println("[pholcus] http server Running on ", addr)
	err := http.ListenAndServe(addr, nil) //设置监听的端口
	if err != nil {
		reporter.Fatal("Http ListenAndServe: ", err)
	}
}
예제 #30
0
func main() {

	router1 := httprouter.New()
	router1.GET("/keys", GetKeyServer3000)
	router1.PUT("/keys/:key_id/:value", PutServer1)
	server := http.Server{
		Addr:    "0.0.0.0:3000",
		Handler: router1,
	}
	router2 := httprouter.New()
	router2.GET("/keys", GetKeyServer3001)
	router2.PUT("/keys/:key_id/:value", PutServer2)

	go func() {
		http.ListenAndServe("localhost:3001", router2)
	}()

	router3 := httprouter.New()
	router3.GET("/keys", GetKeyServer3002)
	router3.PUT("/keys/:key_id/:value", PutServer3)

	go func() {
		http.ListenAndServe("localhost:3002", router3)
	}()

	server.ListenAndServe()

}