コード例 #1
0
// This is an example for serving HTTP, HTTPS, and GoRPC/TLS on the same port.
func Example_recursiveCmux() {
	// Create the TCP listener.
	l, err := net.Listen("tcp", "127.0.0.1:50051")
	if err != nil {
		log.Fatal(err)
	}

	// Create a mux.
	tcpm := cmux.New(l)

	// We first match on HTTP 1.1 methods.
	httpl := tcpm.Match(cmux.HTTP1Fast())

	// If not matched, we assume that its TLS.
	tlsl := tcpm.Match(cmux.Any())
	tlsl = tlsListener(tlsl)

	// Now, we build another mux recursively to match HTTPS and GoRPC.
	// You can use the same trick for SSH.
	tlsm := cmux.New(tlsl)
	httpsl := tlsm.Match(cmux.HTTP1Fast())
	gorpcl := tlsm.Match(cmux.Any())

	go recursiveServeHTTP(httpl)
	go recursiveServeHTTP(httpsl)
	go recursiveServeRPC(gorpcl)

	go tlsm.Serve()
	tcpm.Serve()
}
コード例 #2
0
ファイル: example_tls_test.go プロジェクト: soheilhy/cmux
// This is an example for serving HTTP and HTTPS on the same port.
func Example_bothHTTPAndHTTPS() {
	// Create the TCP listener.
	l, err := net.Listen("tcp", "127.0.0.1:50051")
	if err != nil {
		log.Panic(err)
	}

	// Create a mux.
	m := cmux.New(l)

	// We first match on HTTP 1.1 methods.
	httpl := m.Match(cmux.HTTP1Fast())

	// If not matched, we assume that its TLS.
	//
	// Note that you can take this listener, do TLS handshake and
	// create another mux to multiplex the connections over TLS.
	tlsl := m.Match(cmux.Any())

	go serveHTTP1(httpl)
	go serveHTTPS(tlsl)

	if err := m.Serve(); !strings.Contains(err.Error(), "use of closed network connection") {
		panic(err)
	}
}
コード例 #3
0
ファイル: example_test.go プロジェクト: imjerrybao/cmux
func Example() {
	l, err := net.Listen("tcp", "127.0.0.1:50051")
	if err != nil {
		log.Fatal(err)
	}

	m := cmux.New(l)

	// We first match the connection against HTTP2 fields. If matched, the
	// connection will be sent through the "grpcl" listener.
	grpcl := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
	//Otherwise, we match it againts a websocket upgrade request.
	wsl := m.Match(cmux.HTTP1HeaderField("Upgrade", "websocket"))

	// Otherwise, we match it againts HTTP1 methods. If matched,
	// it is sent through the "httpl" listener.
	httpl := m.Match(cmux.HTTP1Fast())
	// If not matched by HTTP, we assume it is an RPC connection.
	rpcl := m.Match(cmux.Any())

	// Then we used the muxed listeners.
	go serveGRPC(grpcl)
	go serveWS(wsl)
	go serveHTTP(httpl)
	go serveRPC(rpcl)

	m.Serve()
}
コード例 #4
0
ファイル: main.go プロジェクト: dgraph-io/dgraph
func setupServer(che chan error) {
	go worker.RunServer() // For internal communication.

	l, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
	if err != nil {
		log.Fatal(err)
	}

	tcpm := cmux.New(l)
	httpl := tcpm.Match(cmux.HTTP1Fast())
	grpcl := tcpm.MatchWithWriters(
		cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
	http2 := tcpm.Match(cmux.HTTP2())

	http.HandleFunc("/query", queryHandler)
	http.HandleFunc("/debug/store", storeStatsHandler)
	http.HandleFunc("/admin/shutdown", shutDownHandler)
	http.HandleFunc("/admin/backup", backupHandler)
	// Initilize the servers.
	go serveGRPC(grpcl)
	go serveHTTP(httpl)
	go serveHTTP(http2)

	go func() {
		<-closeCh
		// Stops listening further but already accepted connections are not closed.
		l.Close()
	}()

	log.Println("grpc server started.")
	log.Println("http server started.")
	log.Println("Server listening on port", *port)

	// Start cmux serving.
	che <- tcpm.Serve()
}
コード例 #5
0
ファイル: main.go プロジェクト: henriAbel/ircbot
func StartWeb() {
	var DefaultDevStack = []rest.Middleware{
		&rest.TimerMiddleware{},
		&rest.RecorderMiddleware{},
		&rest.RecoverMiddleware{
			EnableResponseStackTrace: true,
		},
		&rest.JsonIndentMiddleware{},
		&rest.ContentTypeCheckerMiddleware{},
	}

	jwtMiddleware := &jwt.JWTMiddleware{
		Key:        []byte("VerySecrestKey"),
		Realm:      "jwt auth",
		Timeout:    time.Hour,
		MaxRefresh: time.Hour * 24,
		Authenticator: func(userId string, password string) bool {
			return password == irc.GetWebPassword()
		}}

	api := rest.NewApi()
	api.Use(DefaultDevStack...)
	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			if len(irc.GetWebPassword()) > 1 {
				token := request.Request.URL.Query()["authorization"]
				if len(token) > 0 {
					request.Header.Add("Authorization", "Bearer "+token[0])
				}
				return request.URL.Path != "/login"
			}
			return false
		},
		IfTrue: jwtMiddleware,
	})

	service := NewLinkService()

	apiRouter, _ := rest.MakeRouter(
		rest.Post("/login", jwtMiddleware.LoginHandler),
		rest.Get("/refresh_token", jwtMiddleware.RefreshHandler),
		rest.Get("/config", service.GetConfig),
		rest.Get("/links", service.GetAll),
		rest.Get("/links/count", service.GetCount),
		rest.Get("/raw/:id/:type", service.Raw),
		rest.Get("/stat/all", service.GetAllStats),
	)
	api.SetApp(apiRouter)

	listeningPort := fmt.Sprintf(":%d", irc.GetWebPort())
	enableTls := len(irc.GetCertFile()) > 0 && len(irc.GetKeyFile()) > 0
	mux := http.NewServeMux()
	mux.Handle("/api/", http.StripPrefix("/api", api.MakeHandler()))
	mux.Handle("/bower_components/", http.FileServer(http.Dir("./web/static/")))
	mux.Handle("/", http.FileServer(http.Dir("./web/static/app/")))

	l, err := net.Listen("tcp", listeningPort)
	if err != nil {
		log.Fatal(err)
	}
	m := cmux.New(l)

	httpl := m.Match(cmux.HTTP1Fast())
	if enableTls {
		tlsl := m.Match(cmux.Any())
		redirectMux := http.NewServeMux()
		redirectMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			u := r.URL
			u.Host = r.Host
			u.Scheme = "https"
			http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
		})
		go serveHTTPS(tlsl, mux)
		go serveHTTP1(httpl, redirectMux)
	} else {
		go serveHTTP1(httpl, mux)
	}

	if err := m.Serve(); !strings.Contains(err.Error(), "use of closed network connection") {
		panic(err)
	}

}