本文整理汇总了Golang中http.NewServeMux函数的典型用法代码示例。如果您正苦于以下问题:Golang NewServeMux函数的具体用法?Golang NewServeMux怎么用?Golang NewServeMux使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewServeMux函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewServer
/*
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
}
示例2: realInit
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
}
示例3: NewCoordinator
func NewCoordinator(secret []byte) *Coordinator {
return &Coordinator{
workers: make(map[string]*WorkerRegistration),
secret: secret,
Mux: http.NewServeMux(),
}
}
示例4: BenchmarkStaticFileOverTCPNoMultiplex
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()
}
示例5: Run
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)
}
}
示例6: startAllServers
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
}
示例7: NewWebInterface
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
}
示例8: BenchmarkHelloWorldOverTCPNoMultiplex
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()
}
示例9: httpLauncher
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)
}
}
示例10: Run
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()
}
示例11: NewServer
// 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
}
示例12: Run
//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()
}
示例13: main
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)
}
}
示例14: New
func New() *Server {
return &Server{mux: http.NewServeMux()}
}
示例15: init
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)