Exemplo n.º 1
0
/*
Creates new rocket's server bound to specified addr.
A Trivial example server:

    package main

    import "rocket"

    func main() {
         s := rocket.NewServer("ws://localhost:8080")
         s.Handle("/echo", rocket.NewJSONHandler())
         s.ListenAndServe()
    }
*/
func NewServer(addr string) *Server {
	s := new(Server)
	s.Addr, s.Handler = addr, http.NewServeMux()
	s.handlers = make(handlerMap)
	s.Log = log.New(os.Stderr, "S : ", log.LstdFlags)
	return s
}
Exemplo n.º 2
0
func realInit(w http.ResponseWriter, r *http.Request) bool {
	ctx := appengine.NewContext(r)

	errf := func(format string, args ...interface{}) bool {
		ctx.Errorf("In init: "+format, args...)
		http.Error(w, fmt.Sprintf(format, args...), 500)
		return false
	}

	config, err := serverconfig.Load("./config.json")
	if err != nil {
		return errf("Could not load server config: %v", err)
	}

	// Update the config to use the URL path derived from the first App Engine request.
	// TODO(bslatkin): Support hostnames that aren't x.appspot.com
	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}

	baseURL := fmt.Sprintf("%s://%s/", scheme, appengine.DefaultVersionHostname(ctx))
	ctx.Infof("baseurl = %q", baseURL)
	config.Obj["baseURL"] = baseURL

	root.mux = http.NewServeMux()
	err = config.InstallHandlers(root.mux, baseURL, r)
	if err != nil {
		return errf("Error installing handlers: %v", err)
	}

	return true
}
Exemplo n.º 3
0
func NewCoordinator(secret []byte) *Coordinator {
	return &Coordinator{
		workers: make(map[string]*WorkerRegistration),
		secret:  secret,
		Mux:     http.NewServeMux(),
	}
}
Exemplo n.º 4
0
func BenchmarkStaticFileOverTCPNoMultiplex(b *testing.B) {
	b.StopTimer()
	fcgiMux := http.NewServeMux()
	fcgiMux.Handle("/static/", http.FileServer("_test/", "/static"))
	if err := createStaticTestFile(); err != nil {
		log.Print("Failed to create test file:", err)
		return
	}
	tcplisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("Listen error:", err)
		return
	}
	weblisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("net.Listen error:", err)
		return
	}
	url := "http://" + weblisten.Addr().String() + "/static/fcgi_test.html"
	handler, err := Handler([]Dialer{
		NewDialer("tcp", tcplisten.Addr().String()),
	})
	if err != nil {
		log.Print("Handler error:", err)
		return
	}
	http.Handle("/static/", handler)
	go http.Serve(tcplisten, fcgiMux)
	go http.Serve(weblisten, nil)
	b.StartTimer()
	log.Print("Loop starting...", b.N)
	for i := 0; i < b.N; i++ {
		response, _, err := http.Get(url)
		if err != nil {
			log.Print("http.Get error:", err)
		}
		if response == nil {
			log.Print("Nil response.")
			continue
		}
		if response.StatusCode != 200 {
			log.Print("Bad response status:", response.StatusCode)
			continue
		}
		if response != nil {
			_, err := ioutil.ReadAll(response.Body)
			if err != nil {
				log.Print("ioutil.ReadAll error:", err)
				break
			}
			response.Body.Close()
			// b.SetBytes(int64(len(body)))
		}
	}
	weblisten.Close()
	tcplisten.Close()
	removeStaticTestFile()
}
Exemplo n.º 5
0
Arquivo: web.go Projeto: ality/web.go
func (s *Server) Run(addr string) {
	mux := http.NewServeMux()
	mux.Handle("/", s)
	s.Logger.Printf("web.go serving %s\n", addr)
	err := http.ListenAndServe(addr, mux)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemplo n.º 6
0
func startAllServers(t *testing.T) (tcplisten, unixlisten, weblisten net.Listener) {
	var fcgiMux = http.NewServeMux()
	// define the muxer for the FCGI responders to use
	fcgiMux.Handle("/hello/", http.HandlerFunc(HelloServer))
	fcgiMux.Handle("/notfound/", http.HandlerFunc(http.NotFound))
	fcgiMux.Handle("/connection/", http.HandlerFunc(func(conn http.ResponseWriter, req *http.Request) {
		conn.SetHeader("Connection", "keep-alive")
		io.WriteString(conn, "connection test")
	}))
	fcgiMux.Handle("/static/", http.FileServer("_test", "/static"))
	if err := createStaticTestFile(); err != nil {
		t.Fatal(err)
		return
	}
	// then start the responders
	tcplisten, _ = net.Listen("tcp", ":0")
	go Serve(tcplisten, fcgiMux)
	unixlisten, _ = net.Listen("unix", "_test/unixsocket")
	go Serve(unixlisten, fcgiMux)

	// define the muxer for the http server to use
	// (all requests go to the pool of listeners)
	wd, _ := os.Getwd()
	handler, err := Handler([]Dialer{
		NewDialer("tcp", tcplisten.Addr().String()),
		NewDialer("unix", unixlisten.Addr().String()),
		NewDialer("exec", wd+"/_test/listener_test_exec.out"),
	})
	if err != nil {
		t.Fatal(err)
		return
	}
	webMux := http.NewServeMux()
	webMux.Handle("/", handler)

	// start the web server
	weblisten, _ = net.Listen("tcp", ":0")
	go http.Serve(weblisten, webMux)

	// return all the data
	return tcplisten, unixlisten, weblisten
}
Exemplo n.º 7
0
func NewWebInterface(addr string, cm *CallManager, rt RoutingTable) *WebInterface {
	wi := new(WebInterface)
	wi.addr = addr
	wi.cm = cm
	wi.rt = rt
	wi.sm = http.NewServeMux()
	wi.reqcounter = expvar.NewInt("")

	wi.sm.Handle("/", http.HandlerFunc(wi.getDummy()))

	return wi
}
Exemplo n.º 8
0
func BenchmarkHelloWorldOverTCPNoMultiplex(b *testing.B) {
	b.StopTimer()
	fcgiMux := http.NewServeMux()
	fcgiMux.Handle("/hello/", http.HandlerFunc(func(conn http.ResponseWriter, req *http.Request) { conn.Write(helloWorldBytes) }))
	tcplisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("Listen error:", err)
		return
	}
	weblisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("net.Listen error:", err)
		return
	}
	url := "http://" + weblisten.Addr().String() + "/hello/"
	handler, err := Handler([]Dialer{
		NewDialer("tcp", tcplisten.Addr().String()),
	})
	if err != nil {
		log.Print("Handler error:", err)
		return
	}
	http.Handle("/hello/", handler)
	go http.Serve(tcplisten, fcgiMux)
	go http.Serve(weblisten, nil)
	b.StartTimer()
	log.Print("Loop starting...", b.N)
	for i := 0; i < b.N; i++ {
		response, _, err := http.Get(url)
		if err != nil {
			log.Print("http.Get error:", err)
		}
		if response == nil {
			log.Print("Nil response.")
			continue
		}
		if response.StatusCode != 200 {
			log.Print("Bad response status:", response.StatusCode)
			continue
		}
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			log.Print("ioutil.ReadAll error:", err)
			break
		}
		response.Body.Close()
		b.SetBytes(int64(len(body)))
	}
	weblisten.Close()
	tcplisten.Close()
	removeStaticTestFile()
}
Exemplo n.º 9
0
func httpLauncher(pattern string, handler func(http.ResponseWriter, *http.Request)) func([][]byte) {
	return func(data [][]byte) {
		addr := ":" + string(data[1])
		mux, ok := httpHandlers[addr]
		if !ok {
			mux = http.NewServeMux()
			go http.ListenAndServe(addr, mux)
			httpHandlers[addr] = mux
			println("adding http server for", addr)
		}
		mux.HandleFunc(pattern, handler)
	}
}
Exemplo n.º 10
0
func (s *Server) Run(addr string) {
	s.initServer()

	mux := http.NewServeMux()
	mux.Handle("/", s)
	s.Logger.Printf("web.go serving %s\n", addr)

	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
	s.l = l
	err = http.Serve(s.l, mux)
	s.l.Close()
}
Exemplo n.º 11
0
// Returns an API Server
func NewServer(handler Handler, adr string) *Server {
	server := new(Server)
	server.handler = handler
	server.servmux = http.NewServeMux()

	con, err := net.Listen("tcp", adr)
	if err != nil {
		log.Error("API: Couldn't create listener socket: %s\n", err)
	}

	// Add handling function at root, delegating everything to the handler
	server.servmux.HandleFunc("/", func(httpresp http.ResponseWriter, httpreq *http.Request) {
		log.Debug("API: Connection on url %s\n", httpreq.URL)

		resp := &ResponseWriter{httpresp}

		var req *Request
		if req = NewRequest(resp, httpreq); req == nil {
			log.Error("API: Couldn't create request object")
			return
		}

		handler.Handle(resp, req)

		// TODO: Remove that! Shouldn't be here!!
		// Read the rest, so we don't cause Broken Pipe on the other end if we don't read to the end
		ioutil.ReadAll(req.Body)
	})

	// Start serving the API on another thread
	go func() {
		log.Debug("API: Starting API server on adr %s\n", adr)
		err = http.Serve(con, server.servmux)
		con.Close()

		if err != nil {
			log.Fatal("API: Serve error: ", err.String())
		}
	}()

	return server
}
Exemplo n.º 12
0
//Runs the web application and serves http requests
func (s *Server) Run(addr string) {
	s.initServer()

	mux := http.NewServeMux()

	mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
	mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
	mux.Handle("/debug/pprof/heap", http.HandlerFunc(pprof.Heap))
	mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
	mux.Handle("/", s)

	s.Logger.Printf("web.go serving %s\n", addr)

	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
	s.l = l
	err = http.Serve(s.l, mux)
	s.l.Close()
}
func main() {
	flag.Parse()

	sharedSecret = os.Getenv("GARAGE_SECRET")
	if len(sharedSecret) == 0 {
		fmt.Fprintf(os.Stderr,
			"No GARAGE_SECRET environment variable set.\n")
		os.Exit(1)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/", HandleRoot)
	mux.HandleFunc("/garage", HandleGarage)

	fmt.Printf("Starting to listen on http://%v/\n", *listen)
	err := http.ListenAndServe(*listen, mux)
	if err != nil {
		fmt.Fprintf(os.Stderr,
			"Error in http server: %v\n", err)
		os.Exit(1)
	}
}
Exemplo n.º 14
0
func New() *Server {
	return &Server{mux: http.NewServeMux()}
}
Exemplo n.º 15
0
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package appengine

import (
	"fmt"
	"http"

	"camli/blobserver"
	"camli/serverconfig"
)

var mux = http.NewServeMux()

func init() {
	http.Handle("/", mux)
}

func exitFailure(pattern string, args ...interface{}) {
	panic(fmt.Sprintf(pattern, args...))
}

func init() {
	blobserver.RegisterStorageConstructor("appengine", blobserver.StorageConstructor(newFromConfig))

	config, err := serverconfig.Load("./config.json")
	if err != nil {
		exitFailure("Could not load server config: %v", err)
Exemplo n.º 16
0
func NewServeMux(sio *SocketIO) *ServeMux {
	return &ServeMux{http.NewServeMux(), sio}
}
Exemplo n.º 17
0
func New() *Server {
	return &Server{
		premux: make([]HandlerPicker, 0),
		mux:    http.NewServeMux(),
	}
}
Exemplo n.º 18
0
func BenchmarkHelloWorldOverTCPWithMultiplex(b *testing.B) {
	b.StopTimer()
	var C = 50 // number of simultaneous clients
	fcgiMux := http.NewServeMux()
	fcgiMux.Handle("/hello/", http.HandlerFunc(func(conn http.ResponseWriter, req *http.Request) { conn.Write(helloWorldBytes) }))
	tcplisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("Listen error:", err)
		return
	}
	weblisten, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Print("net.Listen error:", err)
		return
	}
	url := "http://" + weblisten.Addr().String() + "/hello/"
	handler, err := Handler([]Dialer{
		NewDialer("tcp", tcplisten.Addr().String()),
	})
	if err != nil {
		log.Print("Handler error:", err)
		return
	}
	http.Handle("/hello/", handler)
	go http.Serve(tcplisten, fcgiMux)
	go http.Serve(weblisten, nil)

	// allow this many simultaneous connections to the webserver
	start := make(chan bool, C)
	for i := 0; i < C; i++ {
		start <- true
	}
	done := make(chan bool, b.N) // for syncing all the multiplex goroutines
	b.StartTimer()
	log.Print("Loop starting...", b.N)
	for i := 0; i < b.N; i++ {
		go func() {
			<-start
			defer func() {
				done <- true
				start <- true
			}()
			response, _, err := http.Get(url)
			if err != nil {
				log.Print("http.Get error:", err)
			}
			if response == nil {
				log.Print("Nil response.")
				return
			}
			if response.StatusCode != 200 {
				log.Print("Bad response status:", response.StatusCode)
				return
			}
			if response != nil {
				body, err := ioutil.ReadAll(response.Body)
				if err != nil {
					log.Print("ioutil.ReadAll error:", err)
					return
				}
				b.SetBytes(int64(len(body)))
				response.Body.Close()
			}
		}()
	}
	for i := 0; i < b.N; i++ {
		<-done
	}
	log.Print("Finished.")
	weblisten.Close()
	tcplisten.Close()
	removeStaticTestFile()
}