當前位置: 首頁>>代碼示例>>Golang>>正文


Golang http.Serve函數代碼示例

本文整理匯總了Golang中http.Serve函數的典型用法代碼示例。如果您正苦於以下問題:Golang Serve函數的具體用法?Golang Serve怎麽用?Golang Serve使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Serve函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: 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()
}
開發者ID:gnanderson,項目名稱:fcgigo,代碼行數:58,代碼來源:oldtests.go

示例2: 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()
}
開發者ID:gnanderson,項目名稱:fcgigo,代碼行數:52,代碼來源:oldtests.go

示例3: serveTestFiles

func serveTestFiles(t *testing.T) (l net.Listener, err os.Error) {
	foundValidPort := false
	var port_str string
	for !foundValidPort {
		port := (rand.Int() & 0x7FFF) + 0x08000
		port_str = strconv.Itoa(port)
		addr, err := net.ResolveTCPAddr("127.0.0.1:" + port_str)
		if err != nil {
			t.Error("Create TCP Address: ", err.String())
			return nil, err
		}
		l, err = net.ListenTCP("tcp4", addr)
		if err != nil {
			if err == os.EADDRINUSE || strings.LastIndex(err.String(), os.EADDRINUSE.String()) != -1 {
				continue
			}
			t.Error("Unable to listen on TCP port: ", err.String())
			return l, err
		}
		foundValidPort = true
	}
	OverrideRapleafHostPort("127.0.0.1", port_str)
	go http.Serve(l, http.HandlerFunc(ServeTestHTTP))
	return l, err
}
開發者ID:pomack,項目名稱:rapleaf-bindings,代碼行數:25,代碼來源:rapleaf_test.go

示例4: listenAndServe

func listenAndServe(addr string, certFile string, keyFile string, caFile string) os.Error {
	config := &tls.Config{
		Rand:               rand.Reader,
		Time:               time.Seconds,
		NextProtos:         []string{"http/1.1"},
		AuthenticateClient: true,
		CipherSuites:       []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
	}

	rootCert, err := ioutil.ReadFile(caFile)
	if err != nil {
		return err
	}
	config.RootCAs = x509.NewCertPool()
	if !config.RootCAs.AppendCertsFromPEM(rootCert) {
		return os.NewError("Failed to add root certificate.")
	}

	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return err
	}

	conn, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}

	tlsListener := tls.NewListener(conn, config)
	return http.Serve(tlsListener, nil)
}
開發者ID:Crest,項目名稱:gresec,代碼行數:32,代碼來源:gresec.go

示例5: main

// The Router application registers RPC listeners to accept from the initiators
// then registers RPC clients to each of the external services it may call.
func main() {

	var err os.Error

	// Pull in command line options or defaults if none given
	flag.Parse()

	f, err := os.OpenFile(*skylib.LogFileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err == nil {
		defer f.Close()
		log.SetOutput(f)
	}

	skylib.Setup("Watcher.Generic") // Change this to be more descriptive

	rpc.HandleHTTP()

	go monitorServices()

	portString := fmt.Sprintf("%s:%d", *skylib.BindIP, *skylib.Port)

	l, e := net.Listen("tcp", portString)
	if e != nil {
		log.Fatal("listen error:", e)
	}
	log.Println("Starting server")
	http.Serve(l, nil)

}
開發者ID:repos-go,項目名稱:skynet,代碼行數:31,代碼來源:generic.go

示例6: Serve

// At the moment, this can start more than one Server on the same
// port, which could be a problem.
func (self *RpcService) Serve(done chan bool) {
	portString := fmt.Sprintf("%s:%d", self.IPAddress, self.Port)
	log.Println(portString)

	l, e := net.Listen("tcp", portString)
	if e != nil {
		log.Fatal("listen error:", e)
	}
	defer l.Close()

	switch self.Protocol {
	default:
		rpc.HandleHTTP() // Seems safe to call multiple times, but must
		// that precede net.Listen()?
		log.Println("Starting http server")
		http.Serve(l, nil)
	case "json":
		log.Println("Starting jsonrpc server")
		for {
			conn, err := l.Accept()
			if err != nil {
				panic(err.String())
			}
			jsonrpc.ServeConn(conn)
		}
	}
	done <- true // This may never occur.
}
開發者ID:andradeandrey,項目名稱:skynet,代碼行數:30,代碼來源:rpcservice.go

示例7: Listen

func (this *WebSocketListener) Listen() {
	http.Serve(this.listener, websocket.Handler(func(connection *websocket.Conn) {
		// The HTTP package creates the goroutine itself. No need for us to do it.
		// Set the RemoteAddr here because of Go Bug #1636
		this.ConnectionHandler(this.ircd, connection, connection.Request.RemoteAddr)
	}))
}
開發者ID:ahf,項目名稱:ircd-novo,代碼行數:7,代碼來源:listeners.go

示例8: main

func main() {

	// Pull in command line options or defaults if none given
	flag.Parse()

	f, err := os.OpenFile(*skylib.LogFileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err == nil {
		defer f.Close()
		log.SetOutput(f)
	}

	skylib.Setup(sName)

	r := NewGetUserDataService()

	rpc.Register(r)

	rpc.HandleHTTP()

	portString := fmt.Sprintf("%s:%d", *skylib.BindIP, *skylib.Port)

	l, e := net.Listen("tcp", portString)
	if e != nil {
		log.Fatal("listen error:", e)
	}

	log.Println("Starting server")
	http.Serve(l, nil)

}
開發者ID:paulbellamy,項目名稱:skynet,代碼行數:30,代碼來源:service.go

示例9: BenchmarkStaticFileOverHTTPWithMultiplex

func BenchmarkStaticFileOverHTTPWithMultiplex(b *testing.B) {
	b.StopTimer()
	var C = 50 // number of simultaneous clients
	http.Handle("/static/", http.FileServer("_test/", "/static"))
	if err := createStaticTestFile(); err != nil {
		log.Print("Failed to create test file:", 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"
	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(index int) {
			<-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()
			}
		}(i)
	}
	for i := 0; i < b.N; i++ {
		<-done
	}
	weblisten.Close()
	removeStaticTestFile()
}
開發者ID:gnanderson,項目名稱:fcgigo,代碼行數:60,代碼來源:oldtests.go

示例10: main

func main( )
{
	rpc.HandleHTTP();

	l, _ := net.Listen("tcp", ":8089");
	http.Serve(l, http.HandlerFunc( handleRequest ) );
}
開發者ID:nkostelnik,項目名稱:learning,代碼行數:7,代碼來源:main.go

示例11: startHttpServer

func startHttpServer(addr string) (err os.Error) {
	httpPort, err := net.Listen("tcp", addr)
	if err != nil {
		return
	}
	go http.Serve(httpPort, nil)
	return
}
開發者ID:nictuku,項目名稱:chunkymonkey,代碼行數:8,代碼來源:chunkymonkey.go

示例12: Serve

func Serve(listener net.Listener) {
	http.HandleFunc("/", viewHtml)
	http.HandleFunc("/$stats.html", statsHtml)
	http.Handle("/$main.js", stringHandler{"application/javascript", main_js})
	http.Handle("/$main.css", stringHandler{"text/css", main_css})
	http.HandleFunc("/$events/", evServer)

	http.Serve(listener, nil)
}
開發者ID:Br3nda,項目名稱:doozerd,代碼行數:9,代碼來源:web.go

示例13: serveHTTP

// rpc over HTTP
func serveHTTP(addr string) {
	rpc.HandleHTTP()

	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	http.Serve(l, nil)
}
開發者ID:nathankerr,項目名稱:negotiation,代碼行數:10,代碼來源:server.go

示例14: RunServer

func RunServer(addr string) {
	self := new(Server).Init()
	rpc.Register(self)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", addr)
	if e != nil {
		log.Exit("listen error: ", e)
	}
	http.Serve(l, nil)
}
開發者ID:ike-dai,項目名稱:go-simple-kvs,代碼行數:10,代碼來源:kvs.go

示例15: main

//Starts the server
func main() {
	md := NewMatrixDatabase()
	rpc.Register(md)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	http.Serve(l, nil)
}
開發者ID:Altece,項目名稱:Go-Go-Gadget-Repo,代碼行數:11,代碼來源:matrixserver.go


注:本文中的http.Serve函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。