当前位置: 首页>>代码示例>>Golang>>正文


Golang http.Serve函数代码示例

本文整理汇总了Golang中net/http.Serve函数的典型用法代码示例。如果您正苦于以下问题:Golang Serve函数的具体用法?Golang Serve怎么用?Golang Serve使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Serve函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ExampleClient_Listen

func ExampleClient_Listen() {
	config := &ClientConfig{
		User: "username",
		Auth: []AuthMethod{
			Password("password"),
		},
	}
	// Dial your ssh server.
	conn, err := Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()

	// Request the remote side to open port 8080 on all interfaces.
	l, err := conn.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		log.Fatalf("unable to register tcp forward: %v", err)
	}
	defer l.Close()

	// Serve HTTP with your SSH server acting as a reverse proxy.
	http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}
开发者ID:BillTheBest,项目名称:fleet,代码行数:26,代码来源:example_test.go

示例2: run

func (cmd *serveEmbedCmd) run(ctx scope.Context, args []string) error {
	listener, err := net.Listen("tcp", cmd.addr)
	if err != nil {
		return err
	}

	closed := false
	m := sync.Mutex{}
	closeListener := func() {
		m.Lock()
		if !closed {
			listener.Close()
			closed = true
		}
		m.Unlock()
	}

	// Spin off goroutine to watch ctx and close listener if shutdown requested.
	go func() {
		<-ctx.Done()
		closeListener()
	}()

	if err := http.Serve(listener, cmd); err != nil {
		fmt.Printf("http[%s]: %s\n", cmd.addr, err)
		return err
	}

	closeListener()
	ctx.WaitGroup().Done()
	return ctx.Err()
}
开发者ID:logan,项目名称:heim,代码行数:32,代码来源:serve.go

示例3: main

func main() {
	certpath := flag.String("cert", "", "The path to a PEM certificate")
	keypath := flag.String("key", "", "The path to a PEM key")
	flag.Parse()
	if len(*certpath) == 0 || len(*keypath) == 0 {
		flag.PrintDefaults()
		return
	}
	ctx := gossl.NewContext(gossl.SSLv3Method())
	ctx.SetOptions(gossl.OpNoCompression)
	err := ctx.UsePrivateKeyFile(*keypath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	ctx.UseCertificateFile(*certpath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	l, err := net.Listen("tcp", ":8000")
	if err != nil {
		panic(err)
	}
	l, err = gossl.NewListener(l, ctx)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
	})
	http.Serve(l, nil)

}
开发者ID:runcom,项目名称:gossl,代码行数:29,代码来源:httpserver.go

示例4: startServer

func (herd *Herd) startServer(portNum uint, daemon bool) error {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
	if err != nil {
		return err
	}
	http.HandleFunc("/", herd.statusHandler)
	http.HandleFunc("/listReachableSubs", herd.listReachableSubsHandler)
	http.HandleFunc("/listSubs", herd.listSubsHandler)
	http.HandleFunc("/showAliveSubs",
		html.BenchmarkedHandler(herd.showAliveSubsHandler))
	http.HandleFunc("/showAllSubs",
		html.BenchmarkedHandler(herd.showAllSubsHandler))
	http.HandleFunc("/showCompliantSubs",
		html.BenchmarkedHandler(herd.showCompliantSubsHandler))
	http.HandleFunc("/showDeviantSubs",
		html.BenchmarkedHandler(herd.showDeviantSubsHandler))
	http.HandleFunc("/showReachableSubs",
		html.BenchmarkedHandler(herd.showReachableSubsHandler))
	http.HandleFunc("/showSub", html.BenchmarkedHandler(herd.showSubHandler))
	if daemon {
		go http.Serve(listener, nil)
	} else {
		http.Serve(listener, nil)
	}
	return nil
}
开发者ID:keep94,项目名称:Dominator,代码行数:26,代码来源:httpd.go

示例5: main

func main() {
	flag.Parse()

	host := *vhost
	if strings.Contains(*vhost, ":") {
		var err error
		shost, port, err := net.SplitHostPort(*vhost)
		if err != nil {
			log.Fatalf("unable to parse httpsAddr: %s", err)
		}
		host = shost
		if port != "443" {
			host = *vhost
		}
	}

	apiVars.Set("requests", apiRequests)
	staticVars.Set("requests", staticRequests)
	webVars.Set("requests", webRequests)

	index = loadIndex()
	tlsConf := makeTLSConfig(*certPath, *keyPath)

	tlsListener, err := tls.Listen("tcp", *httpsAddr, tlsConf)
	if err != nil {
		log.Fatalf("unable to listen for the HTTPS server on %s: %s", *httpsAddr, err)
	}
	plaintextListener, err := net.Listen("tcp", *httpAddr)
	if err != nil {
		log.Fatalf("unable to listen for the HTTP server on %s: %s", *httpAddr, err)
	}
	l := &listener{tlsListener}

	m := tlsMux(
		host,
		makeStaticHandler())

	adminAddr := net.JoinHostPort("localhost", *adminPort)
	go func() {
		err := http.ListenAndServe(adminAddr, nil)
		if err != nil {
			log.Fatalf("unable to open admin server: %s", err)
		}
	}()

	log.Printf("Booting HTTPS on %s and HTTP on %s", *httpsAddr, *httpAddr)
	go func() {
		err := http.Serve(l, m)
		if err != nil {
			log.Fatalf("https server error: %s", err)
		}
	}()
	err = http.Serve(plaintextListener, plaintextMux(host))
	if err != nil {
		log.Fatalf("http server error: %s", err)
	}
}
开发者ID:jwise,项目名称:howsmyssl,代码行数:57,代码来源:howsmyssl.go

示例6: main

func main() {
	displayConfig()

	if doMemoryProfile {
		log.Info("Memory profiling active")
		profileFile, _ = os.Create("tyk.mprof")
		defer profileFile.Close()
	}

	targetPort := fmt.Sprintf(":%d", config.ListenPort)
	loadAPIEndpoints(http.DefaultServeMux)

	// Handle reload when SIGUSR2 is received
	l, err := goagain.Listener()
	if nil != err {

		// Listen on a TCP or a UNIX domain socket (TCP here).
		l, err = net.Listen("tcp", targetPort)
		if nil != err {
			log.Fatalln(err)
		}
		log.Println("Listening on", l.Addr())

		// Accept connections in a new goroutine.
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		go http.Serve(l, nil)

	} else {

		// Resume accepting connections in a new goroutine.
		log.Println("Resuming listening on", l.Addr())
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		go http.Serve(l, nil)

		// Kill the parent, now that the child has started successfully.
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}

	}

	// Block the main goroutine awaiting signals.
	if _, err := goagain.Wait(l); nil != err {
		log.Fatalln(err)
	}

	// Do whatever's necessary to ensure a graceful exit like waiting for
	// goroutines to terminate or a channel to become closed.
	//
	// In this case, we'll simply stop listening and wait one second.
	if err := l.Close(); nil != err {
		log.Fatalln(err)
	}
	time.Sleep(1e9)
}
开发者ID:rmg,项目名称:tyk,代码行数:57,代码来源:main.go

示例7: main

func main() {
	flag.Parse()

	routeHost, redirectHost := calculateDomains(*rawVHost, *httpsAddr)

	apiVars.Set("requests", apiRequests)
	staticVars.Set("requests", staticRequests)
	webVars.Set("requests", webRequests)

	index = loadIndex()
	tlsConf := makeTLSConfig(*certPath, *keyPath)

	tlsListener, err := tls.Listen("tcp", *httpsAddr, tlsConf)
	if err != nil {
		log.Fatalf("unable to listen for the HTTPS server on %s: %s", *httpsAddr, err)
	}
	plaintextListener, err := net.Listen("tcp", *httpAddr)
	if err != nil {
		log.Fatalf("unable to listen for the HTTP server on %s: %s", *httpAddr, err)
	}
	l := &listener{tlsListener}

	if *acmeURL != "" {
		if !strings.HasPrefix(*acmeURL, "/") &&
			!strings.HasPrefix(*acmeURL, "https://") &&
			!strings.HasPrefix(*acmeURL, "http://") {
			fmt.Fprintf(os.Stderr, "acmeRedirect must start with 'http://', 'https://', or '/' but does not: %#v\n", *acmeURL)
			os.Exit(1)
		}
	}

	m := tlsMux(
		routeHost,
		redirectHost,
		*acmeURL,
		makeStaticHandler(*staticDir, staticVars))

	adminAddr := net.JoinHostPort("localhost", *adminPort)
	go func() {
		err := http.ListenAndServe(adminAddr, nil)
		if err != nil {
			log.Fatalf("unable to open admin server: %s", err)
		}
	}()

	log.Printf("Booting HTTPS on %s and HTTP on %s", *httpsAddr, *httpAddr)
	go func() {
		err := http.Serve(l, m)
		if err != nil {
			log.Fatalf("https server error: %s", err)
		}
	}()
	err = http.Serve(plaintextListener, plaintextMux(redirectHost))
	if err != nil {
		log.Fatalf("http server error: %s", err)
	}
}
开发者ID:alex,项目名称:howsmyssl,代码行数:57,代码来源:howsmyssl.go

示例8: Run

func (p *Proxy) Run() error {
	hl, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return fmt.Errorf("http listen failed: %v", err)
	}
	defer hl.Close()

	hsl, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return fmt.Errorf("https listen failed: %v", err)
	}
	defer hsl.Close()

	p.ul, err = DefaultSocket.Listen()
	if err != nil {
		c, derr := DefaultSocket.Dial()
		if derr == nil {
			c.Close()
			fmt.Println("OK\nA proxy is already running... exiting")
			return nil
		} else if e, ok := derr.(*net.OpError); ok && e.Err == syscall.ECONNREFUSED {
			// Nothing is listening on the socket, unlink it and try again.
			syscall.Unlink(DefaultSocket.Path())
			p.ul, err = DefaultSocket.Listen()
		}
		if err != nil {
			return fmt.Errorf("unix listen failed on %v: %v", DefaultSocket.Path(), err)
		}
	}
	defer p.ul.Close()
	go p.closeOnSignal()
	go p.closeOnUpdate()

	p.httpAddr = hl.Addr().String()
	p.httpsAddr = hsl.Addr().String()
	fmt.Printf("OK\nListening on unix socket=%v http=%v https=%v\n",
		p.ul.Addr(), p.httpAddr, p.httpsAddr)

	result := make(chan error, 2)
	go p.serveUnix(result)
	go func() {
		result <- http.Serve(hl, &httputil.ReverseProxy{
			FlushInterval: 500 * time.Millisecond,
			Director:      func(r *http.Request) {},
		})
	}()
	go func() {
		result <- http.Serve(hsl, &httputil.ReverseProxy{
			FlushInterval: 500 * time.Millisecond,
			Director: func(r *http.Request) {
				r.URL.Scheme = "https"
			},
		})
	}()
	return <-result
}
开发者ID:205c,项目名称:git,代码行数:56,代码来源:proxy.go

示例9: Run

func (this *FrontEnd) Run() error {
	err := make(chan error)
	go func() {
		err <- http.Serve(this.https, this.proxy)
	}()
	go func() {
		err <- http.Serve(this.http, this.proxy)
	}()
	return <-err
}
开发者ID:badgerodon,项目名称:go,代码行数:10,代码来源:frontend.go

示例10: openHTTPServer

// openHTTPServer initializes and opens the HTTP server.
// The store must already be open.
func (m *Main) openHTTPServer(ln net.Listener, peers []string) error {
	// If we have no store then simply start a proxy handler.
	if m.store == nil {
		go http.Serve(ln, &server.ProxyHandler{Peers: peers})
		return nil
	}

	// Otherwise initialize and start handler.
	h := server.NewHandler()
	h.Store = m.store
	go http.Serve(ln, h)

	return nil
}
开发者ID:QY-Y,项目名称:flynn,代码行数:16,代码来源:main.go

示例11: Run

func (this *Server) Run(mode string, addr string, port int) error {
	var tlsConfig *tls.Config
	var err error
	if mode == "https" {
		tlsConfig = &tls.Config{}
		if tlsConfig.NextProtos == nil {
			tlsConfig.NextProtos = []string{"http/1.1"}
		}
		tlsConfig.Certificates = make([]tls.Certificate, 1)
		tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(SslCertificate, SslCertificateKey)
		if err != nil {
			return err
		}
	}

	listenUnix := false
	if strings.HasPrefix(addr, "unix:") {
		listenUnix = true
		addr = addr[5:]
	}

	if listenUnix {
		os.Remove(addr)
		this.listener, err = net.Listen("unix", addr)
		if err == nil {
			os.Chmod(addr, os.FileMode(0666))
			defer os.Remove(addr)
		}
	} else {
		listenAddr := net.JoinHostPort(addr, fmt.Sprintf("%d", port))
		this.listener, err = net.Listen("tcp", listenAddr)
	}
	if err != nil {
		return err
	}
	// defer this.listener.Close()
	this.RunMode = mode

	switch mode {
	case "http":
		http.Serve(this.listener, this.router)
	case "fcgi":
		fcgi.Serve(this.listener, this.router)
	case "https":
		http.Serve(tls.NewListener(this.listener, tlsConfig), this.router)
	default:
		http.Serve(this.listener, this.router)
	}
	return nil
}
开发者ID:xgdapg,项目名称:wtk,代码行数:50,代码来源:server.go

示例12: httpServer

func httpServer(sn *subnet.SubnetManager, publicIP, port string) error {
	overlayListener, err := net.Listen("tcp", net.JoinHostPort(sn.Lease().Network.IP.String(), port))
	if err != nil {
		return err
	}
	publicListener, err := net.Listen("tcp", net.JoinHostPort(publicIP, port))

	http.HandleFunc("/ping", func(http.ResponseWriter, *http.Request) {})
	status.AddHandler(status.SimpleHandler(func() error {
		return pingLeases(sn.Leases())
	}))
	go http.Serve(overlayListener, nil)
	go http.Serve(publicListener, nil)
	return nil
}
开发者ID:eldarion-gondor,项目名称:cli,代码行数:15,代码来源:main.go

示例13: StartServer

func StartServer(portNum uint, manager *filegen.Manager, daemon bool) error {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
	if err != nil {
		return err
	}
	myState := &state{manager}
	http.HandleFunc("/", myState.statusHandler)
	http.HandleFunc("/listGenerators", myState.listGeneratorsHandler)
	if daemon {
		go http.Serve(listener, nil)
	} else {
		http.Serve(listener, nil)
	}
	return nil
}
开发者ID:keep94,项目名称:Dominator,代码行数:15,代码来源:api.go

示例14: NewTribServer

// NewTribServer creates, starts and returns a new TribServer. masterServerHostPort
// is the master storage server's host:port and port is this port number on which
// the TribServer should listen. A non-nil error should be returned if the TribServer
// could not be started.
//
// For hints on how to properly setup RPC, see the rpc/tribrpc package.
func NewTribServer(masterServerHostPort, myHostPort string) (TribServer, error) {
	newStore, err := libstore.NewLibstore(masterServerHostPort, myHostPort, libstore.Never)
	if err != nil {
		return nil, err
	}

	ts := &tribServer{
		myHostPort: myHostPort,
		Libstore:   newStore,
	}

	err = rpc.RegisterName("TribServer", tribrpc.Wrap(ts))
	if err != nil {
		return nil, err
	}

	rpc.HandleHTTP()
	l, err := net.Listen("tcp", myHostPort)
	if err != nil {
		return nil, err
	}
	go http.Serve(l, nil)

	return ts, nil
}
开发者ID:oldady,项目名称:ds_p2,代码行数:31,代码来源:tribserver_impl.go

示例15: NewTribServer

// NewTribServer creates, starts and returns a new TribServer. masterServerHostPort
// is the master storage server's host:port and port is this port number on which
// the TribServer should listen. A non-nil error should be returned if the TribServer
// could not be started.
//
// For hints on how to properly setup RPC, see the rpc/tribrpc package.
func NewTribServer(masterServerHostPort, myHostPort string) (TribServer, error) {
	libStore, err := libstore.NewLibstore(masterServerHostPort, myHostPort, libstore.Never)
	//fmt.Println("Creating new tribServer...")
	if err != nil {
		return nil, err
	}

	var tribServ tribServer = tribServer{
		libStore: libStore,
	}
	l, err2 := net.Listen("tcp", myHostPort)
	if err2 != nil {
		fmt.Println(err2)
		return nil, err2
	}
	//go http.Serve(l, nil)
	err1 := rpc.RegisterName("TribServer", tribrpc.Wrap(&tribServ))
	if err1 != nil {
		fmt.Println(err1)
		return nil, err1
	}
	rpc.HandleHTTP()
	go http.Serve(l, nil)

	return &tribServ, nil
}
开发者ID:aditij1,项目名称:p2aditijakkamat,代码行数:32,代码来源:tribserver_impl.go


注:本文中的net/http.Serve函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。