Exemple #1
0
func runAppServer(serverStopChan chan int, serverResultChan chan error) {
	http.Handle("/app/", http.StripPrefix("/app/", http.FileServer(http.Dir("/home/hduran/Develop/menditor/resources"))))
	http.HandleFunc("/data/", dataHandler) // homepage

	originalListener, err := net.Listen("tcp", fmt.Sprintf(":%d", serveAtPort))
	if err != nil {
		panic(err)
	}

	sl, err := stoppableListener.New(originalListener)
	if err != nil {
		panic(err)
	}

	server := http.Server{}
	var wg sync.WaitGroup
	var serverError error
	go func() {
		wg.Add(1)
		defer wg.Done()
		serverError = server.Serve(sl)
	}()

	select {
	case <-serverStopChan:
		sl.Stop()
	}

	wg.Wait()
	serverResultChan <- serverError
}
Exemple #2
0
func main() {
	originalListener, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}

	sl, err := stoppableListener.New(originalListener)
	if err != nil {
		panic(err)
	}

	http.HandleFunc("/", helloHttp)
	server := http.Server{}

	stop := make(chan os.Signal)
	signal.Notify(stop, syscall.SIGINT)
	var wg sync.WaitGroup
	go func() {
		wg.Add(1)
		defer wg.Done()
		server.Serve(sl)
	}()

	fmt.Printf("Serving HTTP\n")
	select {
	case signal := <-stop:
		fmt.Printf("Got signal:%v\n", signal)
	}
	fmt.Printf("Stopping listener\n")
	sl.Stop()
	fmt.Printf("Waiting on server\n")
	wg.Wait()

}
func (server *TestWebSocketServer) createListener() {
	originalListener, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		panic(err)
	}
	server.listener, err = stoppableListener.New(originalListener)
	if err != nil {
		panic(err)
	}
	server.Url, err = url.Parse("http://" + originalListener.Addr().String())
	if err != nil {
		panic(err)
	}
}
Exemple #4
0
func NewListener(port int, readTimeout, writeTimeout time.Duration) (*Listener, error) {
	originalListener, err := net.Listen("tcp", ":"+strconv.Itoa(port))
	sl, err := stoppableListener.New(originalListener)

	if err != nil {
		return nil, err
	}

	tl := &Listener{
		StoppableListener: sl,
		ReadTimeout:       readTimeout,
		WriteTimeout:      writeTimeout,
	}
	return tl, nil
}
// Run runs a new HTTP service at the given addr, making data requests to the given c.
// Run may be called repeatedly, and each time, will shut down any existing service first.
// Run is NOT threadsafe, and MUST NOT be called concurrently by multiple goroutines.
func (s Server) Run(f GetDataFunc, addr string) error {
	// TODO make an object, which itself is not threadsafe, but which encapsulates all data so multiple
	//      objects can be created and Run.

	if s.stoppableListener != nil {
		log.Infof("Stopping Web Server\n")
		s.stoppableListener.Stop()
		s.stoppableListenerWaitGroup.Wait()
	}
	log.Infof("Starting Web Server\n")

	var err error
	var originalListener net.Listener
	if originalListener, err = net.Listen("tcp", addr); err != nil {
		return err
	}
	if s.stoppableListener, err = stoppableListener.New(originalListener); err != nil {
		return err
	}

	s.getData = f

	sm := http.NewServeMux()
	err = s.registerEndpoints(sm)
	if err != nil {
		return err
	}
	server := &http.Server{
		Addr:           addr,
		Handler:        sm,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	s.stoppableListenerWaitGroup = sync.WaitGroup{}
	s.stoppableListenerWaitGroup.Add(1)
	go func() {
		defer s.stoppableListenerWaitGroup.Done()
		server.Serve(s.stoppableListener)
	}()

	log.Infof("Web server listening on %s", addr)
	return nil
}
Exemple #6
0
func HTTPServe(addr string, timeout int) error {
	hostname, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	originalListener, err := net.Listen("tcp4", addr)
	if err != nil {
		panic(err)
	}
	sl, err := stoppableListener.New(originalListener)
	if err != nil {
		panic(err)
	}

	c := make(chan string)
	go func() {
		logger.Logf("%v: serving on %v\n", hostname, addr)

		// Wait for either timeout or connect from client
		select {
		case <-time.After(time.Duration(timeout) * time.Second):
			{
				logger.Logf("%v: Serve timed out after %v seconds\n", hostname, timeout)
			}
		case client := (<-c):
			{
				logger.Logf("%v: Serve got a connection from %v\n", hostname, client)
			}
		}
		sl.Stop()
	}()

	serveMux := http.NewServeMux()
	serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		logger.Logf("%v: Serve got a connection from %v\n", hostname, r.RemoteAddr)
		fmt.Fprintf(w, "%v", hostname)
		c <- r.RemoteAddr
	})
	err = http.Serve(sl, serveMux)
	if err != nil && err.Error() == "Listener stopped" {
		err = nil
	}
	return err
}
Exemple #7
0
// http server gracefull exit on SIGINT
func (s *Server) Start(mux http.Handler) error {
	if mux == nil {
		mux = http.DefaultServeMux
	}
	originalListener, err := net.Listen("tcp", s.Bind)
	if err != nil {
		return err
	}

	sl, err := stoppableListener.New(originalListener)
	if err != nil {
		return err
	}

	server := http.Server{
		Handler: mux,
	}

	signal.Notify(s.SigChan, syscall.SIGINT)
	var wg sync.WaitGroup
	go func() {
		wg.Add(1)
		defer wg.Done()
		server.Serve(sl)
	}()

	var exitNotice chan error

	select {
	case ch := <-s.StopChan:
		log.Printf("Stopping Server\n")
		exitNotice = ch
	case signal := <-s.SigChan:
		log.Printf("Got signal:%v\n", signal)
	}
	sl.Stop()
	wg.Wait()

	if exitNotice != nil {
		exitNotice <- nil
	}
	return nil
}
Exemple #8
0
func (s *Server) ListenAndServe() {
	defer s.wg.Done()
	s.wg.Add(1)

	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.Addr, s.Port))
	if err != nil {
		logging.GetLogger().Fatalf("Failed to listen on %s:%d: %s", s.Addr, s.Port, err.Error())
	}

	s.lock.Lock()
	s.sl, err = stoppableListener.New(listener)
	if err != nil {
		s.lock.Unlock()
		logging.GetLogger().Fatalf("Failed to create stoppable listener: %s", err.Error())
	}
	s.lock.Unlock()

	http.Serve(s.sl, s.Router)
}
// Run runs a new HTTP service at the given addr, making data requests to the given c.
// Run may be called repeatedly, and each time, will shut down any existing service first.
// Run is NOT threadsafe, and MUST NOT be called concurrently by multiple goroutines.
func Run(c chan DataRequest, addr string) error {
	// TODO make an object, which itself is not threadsafe, but which encapsulates all data so multiple
	//      objects can be created and Run.

	if globalStoppableListener != nil {
		log.Printf("Stopping Web Server\n")
		globalStoppableListener.Stop()
		globalStoppableListenerWaitGroup.Wait()
	}
	log.Printf("Starting Web Server\n")

	var err error
	var originalListener net.Listener
	if originalListener, err = net.Listen("tcp", addr); err != nil {
		return err
	}
	if globalStoppableListener, err = stoppableListener.New(originalListener); err != nil {
		return err
	}

	mgrReqChan = c

	sm := http.NewServeMux()
	RegisterEndpoints(sm)
	server := &http.Server{
		Addr:           addr,
		Handler:        sm,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	globalStoppableListenerWaitGroup = sync.WaitGroup{}
	globalStoppableListenerWaitGroup.Add(1)
	go func() {
		defer globalStoppableListenerWaitGroup.Done()
		server.Serve(globalStoppableListener)
	}()

	log.Printf("Web server listening on %s", addr)
	return nil
}
Exemple #10
0
// Run runs the server if it has any APIs registered on it
func (s *Server) Run() (err error) {

	if len(s.apis) == 0 {
		return errors.New("No APIs defined for server")
	}

	// Server the console swagger UI
	s.router.ServeFiles("/console/*filepath", http.Dir(Config.Server.ConsoleFilesPath))

	// Start a stoppable listener
	var l net.Listener

	if l, err = net.Listen("tcp", s.addr); err != nil {
		return fmt.Errorf("Could not listen in server: %s", err)
	}

	if s.listener, err = stoppableListener.New(l); err != nil {
		return fmt.Errorf("Could not start stoppable listener in server: %s", err)
	}

	logging.Info("Starting server on %s", s.listener.Addr().String())

	s.wg.Add(1)
	defer func() {
		s.wg.Done()
		// don't return an error on server stopped
		if err == stoppableListener.StoppedError {
			err = nil
		}
	}()

	srv := http.Server{
		Handler:      s.router,
		ReadTimeout:  time.Duration(Config.Server.ClientTimeout) * time.Second,
		WriteTimeout: time.Duration(Config.Server.ClientTimeout) * time.Second, // maximum duration before timing out write of the response
	}
	return srv.Serve(s.listener)

}
Exemple #11
0
// Start launches gracefull HTTP listener
func (f *Frontend) Start() error {

	listenAddr := fmt.Sprintf("%s:%d", f.cfg.Host, f.cfg.Port)
	originalListener, err := net.Listen("tcp", listenAddr)
	if err != nil {
		return err
	}

	sl, err := stoppableListener.New(originalListener)
	if err != nil {
		return err
	}

	server := http.Server{Handler: context.ClearHandler(f.router)}

	stop := make(chan os.Signal)
	signal.Notify(stop, syscall.SIGINT)
	var wg sync.WaitGroup
	go func() {
		wg.Add(1)
		defer wg.Done()
		server.Serve(sl)
	}()

	f.log.Info("Start serving HTTP requests at ", listenAddr)
	select {
	case signal := <-stop:
		f.log.Warn("Got signal: ", signal)
	}
	f.log.Info("Stopping listener")
	sl.Stop()
	f.log.Info("Waiting on server")
	wg.Wait()

	return nil
}