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


Golang Server.ListenAndServe方法代碼示例

本文整理匯總了Golang中net/http.Server.ListenAndServe方法的典型用法代碼示例。如果您正苦於以下問題:Golang Server.ListenAndServe方法的具體用法?Golang Server.ListenAndServe怎麽用?Golang Server.ListenAndServe使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net/http.Server的用法示例。


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

示例1: serveWebsite

// Serve the website. This function blocks.
func serveWebsite() {
	port := 8080

	// Sanity check to make sure we're in the right directory.
	_, err := os.Stat("static/font.png")
	if err != nil {
		log.Fatal("You must be in the trs80 source directory (github.com/lkesteloot/trs80)")
	}

	// Create handlers.
	handlers := http.NewServeMux()
	handlers.Handle("/", webutil.GetHandler(http.HandlerFunc(homeHandler)))
	handlers.Handle("/ws", websocket.Handler(wsHandler))
	handlers.Handle("/static/", http.StripPrefix("/static/",
		http.FileServer(http.Dir("static"))))

	// Create server.
	address := fmt.Sprintf(":%d", port)
	server := http.Server{
		Addr:           address,
		Handler:        webutil.LoggingHandler(handlers),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: http.DefaultMaxHeaderBytes,
	}

	// Start serving.
	log.Printf("Serving website on %s", address)
	err = server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
開發者ID:remogatto,項目名稱:trs80,代碼行數:34,代碼來源:web.go

示例2: main

func main() {
	Data[1] = "a"
	Data[2] = "b"
	Data[3] = "c"
	Data[4] = "d"
	Data[5] = "e"
	Data[6] = "f"
	Data[7] = "g"
	Data[8] = "h"
	Data[9] = "i"
	Data[10] = "j"

	for _, each := range Instances {
		Cache[g_p(each)] = each
	}

	for k, _ := range Data {
		Cache[g_p(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range Cache {
		S_keys = append(S_keys, k)
	}

	sort.Strings(S_keys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", put_h)
	mux.GET("/keys/:key", h_get)
	server := http.Server{
		Addr:    "0.0.0.0:8187",
		Handler: mux,
	}
	server.ListenAndServe()
}
開發者ID:onkarganjewar,項目名稱:CMPE273_Lab-3,代碼行數:34,代碼來源:Client.go

示例3: ExampleSessionMux

func ExampleSessionMux() {
	sb := NewSrvSessionBuilder("", "/", "example", 60*60*1000, 10000)
	mux := NewSessionMux("/example", sb)
	mux.HFilterFunc("^.*$", func(hs *HTTPSession) HResult {
		log.D("filt 001")
		return HRES_CONTINUE
	})
	//http://localhost:8080/example/ok
	mux.HFunc("^/ok(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.MsgRes("OK")
		return HRES_RETURN
	})
	//http://localhost:8080/example/data
	mux.HFunc("^/data(\\?.*)?$", func(hs *HTTPSession) HResult {
		var tid int64
		var name string
		err := hs.ValidRVal(`
			tid,R|I,R:0
			name,R|S,L:0`, //valid the argument
			&tid, &name)
		if err != nil {
			return hs.MsgResE(1, err.Error())
		}
		return hs.MsgRes(fmt.Sprintf("%v:%v", tid, name))
	})
	mux.HFunc("^/mdata(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.W.Write([]byte("some data\n"))
		return HRES_RETURN
	})
	s := http.Server{Addr: ":8080", Handler: mux}
	err := s.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}
開發者ID:Centny,項目名稱:Cny4go,代碼行數:35,代碼來源:example_test.go

示例4: main

func main() {
	server := http.Server{
		Addr:    "127.0.0.1:8080",
		Handler: nil,
	}
	server.ListenAndServe()
}
開發者ID:jf,項目名稱:gwp,代碼行數:7,代碼來源:server.go

示例5: main

func main() {
	Values[1] = "z"
	Values[2] = "y"
	Values[3] = "x"
	Values[4] = "q"
	Values[5] = "w"
	Values[6] = "v"
	Values[7] = "u"
	Values[8] = "t"
	Values[9] = "s"
	Values[10] = "r"

	for _, each := range ListOfServers {
		HashingMapping[calculateHashValue(each)] = each
	}

	for k, _ := range Values {
		HashingMapping[calculateHashValue(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range HashingMapping {
		SortedHashingMappingKeys = append(SortedHashingMappingKeys, k)
	}

	sort.Strings(SortedHashingMappingKeys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", putDataTo)
	mux.GET("/keys/:key", getRequest)
	server := http.Server{
		Addr:    "0.0.0.0:8000",
		Handler: mux,
	}
	server.ListenAndServe()
}
開發者ID:vibhutisha,項目名稱:CmpE273_Lab3,代碼行數:34,代碼來源:Client.go

示例6: StartServer

func StartServer(server *http.Server) {
	log.Println("Starting server")
	err := server.ListenAndServe()
	if err != nil {
		log.Fatalln("Error: %v", err)
	}
}
開發者ID:ramigg,項目名稱:GoRethink_TodoDemo,代碼行數:7,代碼來源:server.go

示例7: Run

// Run provides starting of server
func (hs *HttpServer) Run() {
	server := http.Server{
		Addr: hs.Addr,
	}

	go server.ListenAndServe()
}
開發者ID:saromanov,項目名稱:lockwood,代碼行數:8,代碼來源:http_server.go

示例8: main

func main() {
	sourceAddress := ":3000"

	ports := []string{
		":3333",
		":3334",
	}
	hostRing := ring.New(len(ports))
	for _, port := range ports {
		url, _ := url.Parse("http://127.0.0.1" + port)
		hostRing.Value = url
		hostRing = hostRing.Next()
	}

	mutex := sync.Mutex{}
	director := func(request *http.Request) {
		mutex.Lock()
		defer mutex.Unlock()
		request.URL.Scheme = "http"
		request.URL.Host = hostRing.Value.(*url.URL).Host
		hostRing = hostRing.Next()
		fmt.Println(hostRing)
	}
	proxy := &httputil.ReverseProxy{Director: director}
	server := http.Server{
		Addr:    sourceAddress,
		Handler: proxy,
	}
	server.ListenAndServe()
}
開發者ID:yanjinzh6,項目名稱:reverse-proxy,代碼行數:30,代碼來源:main.go

示例9: main

func main() {

	initService()

	var port = flag.String("port", "8000", "please specify the port to start server on")
	flag.Parse()
	logger.Println("Port to start on: " + *port)
	server := http.Server{
		Addr:    ":" + *port,
		Handler: &myHandler{},
	}

	mux = make(map[string]func(http.ResponseWriter, *http.Request))
	mux["/"] = homeHandler
	mux["/healthmetrics"] = healthMetricsHandler
	mux["/addhealthmetrics"] = addHealthMetricsHandler
	mux["/addhealthmetricsform"] = addHealthMetricsFormHandler
	mux["/newuser"] = addUserHandler
	mux["/signupform"] = signupFormHandler
	mux["/login"] = loginHandler
	mux["/loginform"] = loginformHandler
	mux["/logout"] = logoutHandler
	mux["/static"] = staticHandler

	server.ListenAndServe()
}
開發者ID:JJjie,項目名稱:RuCTF-2015,代碼行數:26,代碼來源:server.go

示例10: Serve

func (h *HTTPServer) Serve(launchdSocket string) error {
	proxy := &httputil.ReverseProxy{
		Director:      h.director,
		Transport:     h.transport,
		FlushInterval: 1 * time.Second,
	}

	serv := http.Server{
		Addr:    h.Address,
		Handler: proxy,
	}

	if launchdSocket == "" {
		return serv.ListenAndServe()
	}

	listeners, err := launch.SocketListeners(launchdSocket)
	if err != nil {
		return err
	}

	var t tomb.Tomb

	for _, l := range listeners {
		t.Go(func() error {
			return serv.Serve(l)
		})
	}

	return t.Wait()
}
開發者ID:y-yagi,項目名稱:puma-dev,代碼行數:31,代碼來源:http_darwin.go

示例11: main

func main() {
	var httpServer http.Server
	var httpsServer http.Server
	http2.VerboseLogs = true
	http2.ConfigureServer(&httpsServer, nil)

	http.HandleFunc("/auth", authHandler)
	http.HandleFunc("/", handler)
	http.HandleFunc("/js", jsHandler)

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		log.Println("start http listening :18888")
		httpServer.Addr = ":18888"
		log.Println(httpServer.ListenAndServe())
		wg.Done()
	}()
	go func() {
		log.Println("start https listening :18889")
		httpsServer.Addr = ":18889"
		log.Println(httpsServer.ListenAndServeTLS("server.crt", "server.key"))
		wg.Done()
	}()
	wg.Wait()
}
開發者ID:VViles,項目名稱:curl_as_dsl,代碼行數:26,代碼來源:server.go

示例12: main

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/post/", handleRequest)
	server.ListenAndServe()
}
開發者ID:jf,項目名稱:gwp,代碼行數:7,代碼來源:server.go

示例13: main

func main() {
	var err error
	var f *os.File
	f, err = os.Open("/var/www/index.html")
	if err != nil {
		log.Fatal(err)
	}
	index_bytes, err = ioutil.ReadAll(f)
	if err != nil {
		log.Fatal(err)
	}
	err = f.Close()
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", http_index)
	var srv *http.Server
	srv = &http.Server{
		ReadTimeout: 30 * time.Second,
		Handler:     http.DefaultServeMux,
	}
	go func() {
		var err error
		err = srv.ListenAndServe()
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
	}()
	log.Println("Started")
	select {}
}
開發者ID:khrf,項目名稱:httpd,代碼行數:31,代碼來源:httpd-index.go

示例14: main

func main() {
	Data[1] = "a"
	Data[2] = "b"
	Data[3] = "c"
	Data[4] = "d"
	Data[5] = "e"
	Data[6] = "f"
	Data[7] = "g"
	Data[8] = "h"
	Data[9] = "i"
	Data[10] = "j"

	for _, each := range ServerArr {
		HashMap[getHash(each)] = each
	}

	for k, _ := range Data {
		HashMap[getHash(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range HashMap {
		SortedHashMapKeys = append(SortedHashMapKeys, k)
	}

	sort.Strings(SortedHashMapKeys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", handlePutRequests)
	mux.GET("/keys/:key", handleGetRequests)
	server := http.Server{
		Addr:    "0.0.0.0:8000",
		Handler: mux,
	}
	server.ListenAndServe()
}
開發者ID:sejalgupta3,項目名稱:cmpe273-lab3,代碼行數:34,代碼來源:Client.go

示例15: StartServer

// StartServer Starts the OAuth2 token exchange server. Blocks until the server is killed.
func StartServer() {
	clientKeysFile, err := os.Open(clientKeysPath)
	if err != nil {
		log.Fatal(err)
	}

	clientKeysDecoder := json.NewDecoder(clientKeysFile)
	var clientKeys ClientKeys
	if err = clientKeysDecoder.Decode(&clientKeys); err != nil {
		log.Fatal(err)
	}
	log.Println("Client ID:", clientKeys.ClientID)
	log.Println("Client Secret:", clientKeys.ClientSecret)

	userTokensFile, err := os.OpenFile(userTokensPath, os.O_WRONLY, 0666)
	if err != nil {
		log.Fatal(err)
	}
	defer userTokensFile.Close()

	log.Println("Listening")
	http.HandleFunc("/auth/exchange", makeTokenExchangeHandler(clientKeys, userTokensFile))
	server := http.Server{
		Addr:           ":8080",
		Handler:        nil,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Fatal(server.ListenAndServe())
}
開發者ID:nlefler,項目名稱:jawbone,代碼行數:32,代碼來源:token_exchange.go


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