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


Golang http.Server類代碼示例

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


在下文中一共展示了Server類的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: TestGoRPCBinlogStreamer

// the test here creates a fake server implementation, a fake client
// implementation, and runs the test suite against the setup.
func TestGoRPCBinlogStreamer(t *testing.T) {
	// Listen on a random port
	listener, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatalf("Cannot listen: %v", err)
	}

	// Create a Go Rpc server and listen on the port
	server := rpcplus.NewServer()
	fakeUpdateStream := binlogplayertest.NewFakeBinlogStreamer(t)
	server.Register(gorpcbinlogstreamer.New(fakeUpdateStream))

	// create the HTTP server, serve the server from it
	handler := http.NewServeMux()
	bsonrpc.ServeCustomRPC(handler, server, false)
	httpServer := http.Server{
		Handler: handler,
	}
	go httpServer.Serve(listener)

	// Create a Go Rpc client to talk to the fake tablet
	client := &GoRpcBinlogPlayerClient{}

	// and send it to the test suite
	binlogplayertest.Run(t, client, listener.Addr().String(), fakeUpdateStream)
}
開發者ID:yonglehou,項目名稱:vitess,代碼行數:28,代碼來源:player_test.go

示例3: NewHttpService

func NewHttpService(context interface {
	Acquire()
	Release()
}, server *http.Server) (s *HttpService, err error) {
	s = &HttpService{}
	addr := server.Addr
	if addr == "" {
		addr = ":http"
	}

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

	var w sync.WaitGroup
	w.Add(1)
	context.Acquire()
	go func() {
		defer context.Release()
		l := s.listener
		w.Done()

		server.Serve(l)
	}()

	return
}
開發者ID:albertjin,項目名稱:httputil2,代碼行數:28,代碼來源:service.go

示例4: HandleRoot

func HandleRoot(w http.ResponseWriter, r *http.Request) {
	originalListener, err := net.Listen("tcp", ":8090")
	if err != nil {
		panic(err)
	}

	sl, err := customListener.New(originalListener)
	if err != nil {
		panic(err)
	}

	http.HandleFunc("/", helloHttp)
	server := http.Server{}

	stop := make(chan os.Signal)
	signal.Notify(stop, syscall.SIGINT)
	var wg sync.WaitGroup
	go func() {
		wg.Add(1)
		defer wg.Done()
		server.Serve(sl)
	}()

	fmt.Printf("Serving HTTP\n")
	select {
	case signal := <-stop:
		fmt.Printf("Got signal:%v\n", signal)
	}
	fmt.Printf("Stopping listener\n")
	sl.Stop()
	fmt.Printf("Waiting on server\n")
	wg.Wait()
}
開發者ID:pedrohms,項目名稱:learninggo,代碼行數:33,代碼來源:main.go

示例5: ServeFd

// ServeFD creates an http.Server and sets it up to serve given a socket activated
// argument.
func ServeFd(addr string, handle http.Handler) error {
	ls, e := systemd.ListenFD(addr)
	if e != nil {
		return e
	}

	chErrors := make(chan error, len(ls))

	// We don't want to start serving on these sockets until the
	// "initserver" job has completed. Otherwise required handlers
	// won't be ready.
	<-activationLock

	// Since ListenFD will return one or more sockets we have
	// to create a go func to spawn off multiple serves
	for i := range ls {
		listener := ls[i]
		go func() {
			httpSrv := http.Server{Handler: handle}
			chErrors <- httpSrv.Serve(listener)
		}()
	}

	for i := 0; i < len(ls); i += 1 {
		err := <-chErrors
		if err != nil {
			return err
		}
	}

	return nil
}
開發者ID:houbl,項目名稱:docker,代碼行數:34,代碼來源:server.go

示例6: main

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

示例7: NewHTTP

// NewHTTP returns a ListenProxy with a http as the listening service. This is
// a convenience wrapper kept in place for compatibility with older checkouts.
// Might be removed in the future.
func NewHTTP(handler http.Handler) *ListenProxy {
	lp := NewListenProxy(checker, 10)

	httpServer := http.Server{Addr: ":http", Handler: handler}
	go httpServer.Serve(lp.Listener())
	return lp
}
開發者ID:gitter-badger,項目名稱:serve2,代碼行數:10,代碼來源:http.go

示例8: 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

示例9: RunServer

func RunServer(listenAddress string) (*MemoDb, error) {
	fmt.Println("Nasluch na", listenAddress)
	listener, err := net.Listen("tcp", listenAddress)
	if err != nil {
		return nil, err
	}

	memoDb := &MemoDb{Objects: make(map[string]Object, 0), Listener: listener}

	// obsługa endpointów HTTP przez https://godoc.org/github.com/emicklei/go-restful
	container := restful.NewContainer()
	ws := &restful.WebService{}
	ws.Path("/")
	ws.Route(ws.GET("/").To(memoDb.Help))
	ws.Route(ws.PUT("/v1/objects/{object_id}").To(memoDb.Put))
	ws.Route(ws.GET("/v1/objects/{object_id}").To(memoDb.Get))
	container.Add(ws)

	// nasłuch i obsługa zapytań w tle, w osobnej gorutynie
	go func() {
		server := http.Server{Handler: container}
		server.Serve(listener)
	}()

	return memoDb, nil
}
開發者ID:truszkowski,項目名稱:gomemo,代碼行數:26,代碼來源:main.go

示例10: Listen

func (p *Proxy) Listen() error {
	err := p.cleanup()
	if err != nil {
		return err
	}

	addr, err := net.ResolveUnixAddr("unix", "/var/run/docker.sock")
	if err != nil {
		return err
	}

	raw, err := net.ListenUnix("unix", addr)
	if err != nil {
		return err
	}

	listener := &stoppableListener{
		UnixListener: raw,
		done:         p.done,
	}

	err = os.Chmod("/var/run/docker.sock", 0777)
	if err != nil {
		return err
	}

	server := http.Server{
		Handler: http.HandlerFunc(p.handler),
	}

	return server.Serve(listener)
}
開發者ID:carriercomm,項目名稱:dlite,代碼行數:32,代碼來源:proxy.go

示例11: Serve

// Serve starts the server (http.DefaultServeMux) on given port, loops forever.
func (s *ProxyServer) Serve(port int) error {
	server := http.Server{
		Addr:    fmt.Sprintf(":%d", port),
		Handler: s.mux,
	}
	return server.ListenAndServe()
}
開發者ID:qingyuancloud,項目名稱:qingyuan,代碼行數:8,代碼來源:proxy_server.go

示例12: startP2PServer

func startP2PServer() {
	p2pListener, err := net.Listen("tcp", ":35800")
	if err != nil {
		log.Fatal(err)
	}

	p2psl, err = tcpNew(p2pListener)
	if err != nil {
		log.Fatal(err)
	}

	P2pRouter := httprouter.New()
	P2pRouter.GET("/", sayhello)
	P2pRouter.GET("/pull/:repo/:dataitem/:tag", p2p_pull)
	P2pRouter.GET("/health", p2pHealthyCheckHandler)

	p2pserver := http.Server{Handler: P2pRouter}

	wg.Add(1)
	defer wg.Done()

	log.Info("p2p server start")
	p2pserver.Serve(p2psl)
	log.Info("p2p server stop")

}
開發者ID:asiainfoLDP,項目名稱:datahub,代碼行數:26,代碼來源:p2pserver.go

示例13: listenAndServe

func (h *Handler) listenAndServe(proto, addr, group string) error {
	server := http.Server{
		Addr:    addr,
		Handler: h.mux,
	}

	start := make(chan struct{})

	var l net.Listener
	var err error
	switch proto {
	case "tcp":
		l, err = newTCPSocket(addr, nil, start)
		if err == nil {
			err = writeSpec(group, l.Addr().String())
		}
	case "unix":
		var s string
		s, err = fullSocketAddr(addr)
		if err == nil {
			l, err = newUnixSocket(s, group, start)
		}
	}
	if err != nil {
		return err
	}

	close(start)
	return server.Serve(l)
}
開發者ID:hustcat,項目名稱:degraph,代碼行數:30,代碼來源:api.go

示例14: main

/*
main registers this RP's HTTP request handlers; creates the HTTPS client for issuing OP ID Token requests and starts its HTTP server.
*/
func main() {
	var (
		certPool *x509.CertPool
		server   http.Server
		err      error
	)

	//This aeadCipher is used to encrypt/decrypt the Authn Request Cookie that is used to pass the Authn Request State value
	//from the Authn Request to the Authn Response.
	aeadCipher, err = aead.NewAEADCipher()
	if err != nil {
		return
	}

	//Initialize an HTTPS capable client and replace the default aws HTTP client that doesn't support HTTPS
	certPool = x509.NewCertPool()
	certPool.AppendCertsFromPEM([]byte(certbndl.PemCerts))
	opClient = &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{RootCAs: certPool},
		},
	}

	//Start the service
	server = http.Server{Addr: ":443", ReadTimeout: 10 * time.Minute, WriteTimeout: 10 * time.Minute, ErrorLog: logger.Logger()}
	http.HandleFunc("/login", handleLogin)
	http.HandleFunc("/authn-token", handleAuthnToken)
	logger.Println("Starting oidc on " + exthost + ":443")
	err = server.ListenAndServeTLS("resilient-networks.crt", "resilient-networks.key")
	if err != nil {
		logger.Fatal(err)
	}

}
開發者ID:develrns,項目名稱:resilient,代碼行數:37,代碼來源:oidc.go

示例15: ServeFd

// ServeFD creates an http.Server and sets it up to serve given a socket activated
// argument.
func ServeFd(addr string, handle http.Handler) error {
	ls, e := systemd.ListenFD(addr)
	if e != nil {
		return e
	}

	chErrors := make(chan error, len(ls))

	// Since ListenFD will return one or more sockets we have
	// to create a go func to spawn off multiple serves
	for i := range ls {
		listener := ls[i]
		go func() {
			httpSrv := http.Server{Handler: handle}
			chErrors <- httpSrv.Serve(listener)
		}()
	}

	for i := 0; i < len(ls); i += 1 {
		err := <-chErrors
		if err != nil {
			return err
		}
	}

	return nil
}
開發者ID:jpoimboe,項目名稱:docker,代碼行數:29,代碼來源:api.go


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