Skip to content

Instantly share code, notes, and snippets.

@amitu
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitu/259529fcefe84fef2cc1 to your computer and use it in GitHub Desktop.
Save amitu/259529fcefe84fef2cc1 to your computer and use it in GitHub Desktop.
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