Exemplo n.º 1
0
// Called by http.Server
func (lh *loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	g, err := guid.V4()
	if err != nil {
		msg := "logginghandler: couldn't create request GUID"
		log.Errorln(msg)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}
	rw := &loggingResponseWriter{g, lh.loglevel, w}
	log.Logf(lh.loglevel, "HTTP(%s) %s from %s for %s", g.Short(), r.Method, r.RemoteAddr, r.URL)
	lh.Handler.ServeHTTP(rw, r)
}
Exemplo n.º 2
0
// Serve on a given port
//
// The server will log to the default logger and will gracefully terminate on
// receipt of an interrupt or kill signal.
//
// The following URLs are defined:
//    /
//    /healthz
//    /varz
//    /streamz
//    /birpc
//    /debug/pprof
//
func ServeForever(port int) error {
	addr := ":" + fmt.Sprint(port)
	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Errorln("govtil/net/server: Failed to listen on", port, err)
		return err
	}

	// Close listen port on signals (causes http.Serve() to return)
	sigch := make(chan os.Signal)
	signal.Notify(sigch, []os.Signal{
		syscall.SIGABRT,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGKILL,
		syscall.SIGPWR,
		syscall.SIGQUIT,
		syscall.SIGSTOP,
		syscall.SIGTERM,
	}...)
	go func() {
		sig := <-sigch
		log.Println("govtil/net/server: Closing listen port", l.Addr().String(), "due to signal", sig)
		l.Close()
	}()

	logginghandler := logginghandler.New(http.DefaultServeMux, log.NORMAL)
	err = http.Serve(l, logginghandler)
	if err != nil {
		if vnet.SocketClosed(err) {
			err = nil // closed due to signal, no error
		} else {
			log.Errorln("govtil/net/server:", err)
		}
	}
	log.Println("govtil/net/server: Terminating")
	return err
}
Exemplo n.º 3
0
// Signallistener returns a net.Listener that will be closed when standard OS
// stop signals are received.
func SignalListener(port int) (net.Listener, error) {
	addr := ":" + fmt.Sprint(port)
	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Errorln("govtil/net: Failed to listen on", port, err)
		return nil, err
	}

	// Close listen port on signals (causes http.Serve() to return)
	signal.Go(func(s os.Signal) {
		log.Debugf("govtil/net: Closing listen port %v due to signal %v", l.Addr().String(), s)
		l.Close()
	})

	return l, nil
}