Skip to content

Instantly share code, notes, and snippets.

@amitu

amitu/net.http.diff

Last active Aug 29, 2015
Embed
What would you like to do?
Optionally not creating go routines on HTTP requests: https://groups.google.com/forum/#!topic/golang-nuts/iwCz_pqu8R4
diff -r ceb13960d05b src/pkg/net/http/server.go
--- a/src/pkg/net/http/server.go Thu Mar 13 13:25:59 2014 +0400
+++ b/src/pkg/net/http/server.go Thu Jul 03 21:48:41 2014 +0530
@@ -1615,6 +1615,8 @@
ErrorLog *log.Logger
disableKeepAlives int32 // accessed atomically.
+
+ DisableGoRoutines bool
}
// A ConnState represents the state of a client connection to a server.
@@ -1700,7 +1702,9 @@
// new service goroutine for each. The service goroutines read requests and
// then call srv.Handler to reply to them.
func (srv *Server) Serve(l net.Listener) error {
- defer l.Close()
+ if !srv.DisableGoRoutines {
+ defer l.Close()
+ }
var tempDelay time.Duration // how long to sleep on accept failure
for {
rw, e := l.Accept()
@@ -1726,7 +1730,11 @@
continue
}
c.setState(c.rwc, StateNew) // before Serve can return
- go c.serve()
+ if srv.DisableGoRoutines {
+ c.serve()
+ } else {
+ go c.serve()
+ }
}
}
package main
import (
"fmt"
"net"
"net/http"
"github.com/amitu/gutils"
)
func LimitedListenAndServe(addr string, handler http.Handler, limit int) error {
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}
server := &http.Server{ Handler: handler, DisableGoRoutines: true}
for i := 0; i < limit; i++ {
go server.Serve(listener)
}
return nil
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello")
})
LimitedListenAndServe(":8899", mux, 1)
// http.ListenAndServe(":8899", mux)
gutils.WaitForCtrlC()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.