コード例 #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
ファイル: server.go プロジェクト: icexin/raftkv
func NewServer(cfg *config.Config) (*Server, error) {
	server := &Server{
		cfg:   cfg,
		conns: make(map[string]*rpc.Client),
	}

	// setup listener
	l, err := net.Listen("tcp", cfg.Server.Listen)
	if err != nil {
		return nil, err
	}

	// setup mux
	mux := proto.NewMux(l, nil)
	raftl := mux.Handle(proto.RaftProto)
	msgpackl := mux.Handle(proto.RpcProto)
	httpl := mux.HandleThird(cmux.HTTP1())
	redisl := mux.HandleThird(cmux.Any())

	// setup http server
	go http.Serve(httpl, nil)

	// setup rpc server
	kvs := NewKVS(server)
	rpcServer := rpc.NewServer()
	err = rpcServer.RegisterName("KV", kvs)
	if err != nil {
		return nil, err
	}
	// support msgpack rpc protocol
	go proto.ServeMsgpack(msgpackl, rpcServer)
	// support redis protocol
	go proto.ServeRedis(redisl, rpcServer)

	// setup raft transporter
	advertise, err := net.ResolveTCPAddr("tcp", cfg.Raft.Advertise)
	if err != nil {
		return nil, err
	}
	layer := NewRaftLayer(advertise, raftl)
	trans := raft.NewNetworkTransport(
		layer,
		5,
		time.Second,
		os.Stderr,
	)

	// setup raft fsm
	fsm, err := NewFSM(&cfg.DB)
	if err != nil {
		return nil, err
	}

	// setup raft
	raft, err := NewRaft(&cfg.Raft, fsm, trans)
	if err != nil {
		return nil, err
	}

	server.raftLayer = layer
	server.raftTrans = trans
	server.raft = raft
	server.rpcServer = rpcServer
	server.fsm = fsm
	server.kvs = kvs
	server.mux = mux
	return server, nil
}
コード例 #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)
	}

}