コード例 #1
0
func ExampleEvent() {
	srv := eventsource.NewServer()
	defer srv.Close()
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		return
	}
	defer l.Close()
	http.HandleFunc("/time", srv.Handler("time"))
	go http.Serve(l, nil)
	go TimePublisher(srv)
	stream, err := eventsource.Subscribe("http://127.0.0.1:8080/time", "")
	if err != nil {
		return
	}
	for i := 0; i < TICK_COUNT; i++ {
		ev := <-stream.Events
		fmt.Println(ev.Id(), ev.Event(), ev.Data())
	}

	// Output:
	// 1356998400000000000 Tick 2013-01-01 00:00:00 +0000 UTC
	// 1356998401000000000 Tick 2013-01-01 00:00:01 +0000 UTC
	// 1356998402000000000 Tick 2013-01-01 00:00:02 +0000 UTC
	// 1356998403000000000 Tick 2013-01-01 00:00:03 +0000 UTC
	// 1356998404000000000 Tick 2013-01-01 00:00:04 +0000 UTC
}
コード例 #2
0
ファイル: main.go プロジェクト: BotBotMe/botbot-eventsource
// NewHub returns a pointer to a initialized and running Hub
func NewHub() *Hub {
	// Handle the flags. TODO: add flags for redis
	var dbPath string
	flag.StringVar(&dbPath, "ipdb-path", os.Getenv("IPDB_PATH"),
		"The path to the ip->location DB")
	flag.Parse()

	// Initialze the hub
	log.Println("[Info] Starting the eventsource Hub")

	var db *freegeoip.DB
	var err error
	if dbPath != "" {
		log.Println("[Info] Using ip->location DB ", dbPath)
		db, err = freegeoip.Open(dbPath)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Println("[Info] No ip->location DB provided")
	}

	redisURLString := os.Getenv("REDIS_SSEQUEUE_URL")
	if redisURLString == "" {
		// Use db 2 by default for  pub/sub
		redisURLString = "redis://localhost:6379/2"
	}
	log.Println("[Info] Redis configuration used for pub/sub", redisURLString)
	redisURL, err := nurl.Parse(redisURLString)
	if err != nil {
		log.Fatal("Could not read Redis string", err)
	}

	redisDb, err := strconv.Atoi(strings.TrimLeft(redisURL.Path, "/"))
	if err != nil {
		log.Fatal("[Error] Could not read Redis path", err)
	}

	server := eventsource.NewServer()
	server.AllowCORS = true

	h := Hub{
		Data:       make(map[string][]string),
		Users:      make(map[string]string),
		register:   make(chan Connection, 0),
		unregister: make(chan string, 0),
		messages:   make(chan goredis.Message, 0),
		srv:        server,
		client:     goredis.Client{Addr: redisURL.Host, Db: redisDb},
		ipdb:       db,
	}

	go h.run()
	return &h
}
コード例 #3
0
func newFakeMarathonEndpoint(t *testing.T, configs *configContainer) *endpoint {
	// step: read in the fake responses if required
	initFakeMarathonResponses(t)

	// step: create a fake SSE event service
	eventSrv := eventsource.NewServer()

	// step: fill in the default if required
	defaultConfig := NewDefaultConfig()
	if configs == nil {
		configs = &configContainer{}
	}
	if configs.client == nil {
		configs.client = &defaultConfig
	}
	if configs.server == nil {
		configs.server = &serverConfig{}
	}

	// step: create the HTTP router
	mux := http.NewServeMux()
	mux.HandleFunc("/v2/events", authMiddleware(configs.server, eventSrv.Handler("event")))
	mux.HandleFunc("/", authMiddleware(configs.server, func(writer http.ResponseWriter, reader *http.Request) {
		content, found := fakeResponses[fmt.Sprintf("%s:%s:%s", reader.Method, reader.RequestURI, configs.server.version)]
		if !found {
			http.Error(writer, `{"message": "not found"}`, 404)
			return
		}
		writer.Header().Add("Content-Type", "application/json")
		writer.Write([]byte(content))
	}))

	// step: create HTTP test server
	httpSrv := httptest.NewServer(mux)

	if configs.client.URL == defaultConfig.URL {
		configs.client.URL = getTestURL(httpSrv.URL)
	}

	// step: create the client for the service
	client, err := NewClient(*configs.client)
	if err != nil {
		t.Fatalf("Failed to create the fake client, %s, error: %s", configs.client.URL, err)
	}

	return &endpoint{
		Server: fakeServer{
			eventSrv: eventSrv,
			httpSrv:  httpSrv,
		},
		Client: client,
		URL:    configs.client.URL,
	}
}
コード例 #4
0
ファイル: http.go プロジェクト: dainis/irc_logs
func NewHTTP(history *ElasticHistory, port int) *HTTP {
	h := new(HTTP)

	h.history = history
	h.incomingMessages = make(chan *Message)
	h.port = port
	h.eventSrcSrv = eventsource.NewServer()

	http.HandleFunc("/subscribe", h.eventSrcSrv.Handler("message"))
	http.HandleFunc("/load", h.getLoadHandler())
	http.HandleFunc("/stats/histogram", h.getStatsHistogramHandler())
	http.HandleFunc("/stats/top24h", h.getStatsTopHandler("now-24h", "now"))
	http.HandleFunc("/stats/overall", h.getStatsTopHandler("", ""))

	return h
}
コード例 #5
0
func ExampleRepository() {
	srv := eventsource.NewServer()
	defer srv.Close()
	http.HandleFunc("/articles", srv.Handler("articles"))
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		return
	}
	defer l.Close()
	go http.Serve(l, nil)
	stream, err := eventsource.Subscribe("http://127.0.0.1:8080/articles", "")
	if err != nil {
		return
	}
	go buildRepo(srv)
	// This will receive events in the order that they come
	for i := 0; i < 3; i++ {
		ev := <-stream.Events
		fmt.Println(ev.Id(), ev.Event(), ev.Data())
	}
	stream, err = eventsource.Subscribe("http://127.0.0.1:8080/articles", "1")
	if err != nil {
		fmt.Println(err)
		return
	}
	// This will replay the events in order of id
	for i := 0; i < 3; i++ {
		ev := <-stream.Events
		fmt.Println(ev.Id(), ev.Event(), ev.Data())
	}
	// Output:
	// 2 News Article {"Title":"Governments struggle to control global price of gas","Content":"Hot air...."}
	// 1 News Article {"Title":"Tomorrow is another day","Content":"And so is the day after."}
	// 3 News Article {"Title":"News for news' sake","Content":"Nothing has happened."}
	// 1 News Article {"Title":"Tomorrow is another day","Content":"And so is the day after."}
	// 2 News Article {"Title":"Governments struggle to control global price of gas","Content":"Hot air...."}
	// 3 News Article {"Title":"News for news' sake","Content":"Nothing has happened."}
}
コード例 #6
0
ファイル: jlhose.go プロジェクト: bcampbell/journalisted
func main() {
	flag.Parse()
	db, err := sql.Open("postgres", *dbstring)
	if err != nil {
		glog.Fatal(err)
	}
	if err = db.Ping(); err != nil {
		glog.Fatal(err)
	}
	repo := &articleRepository{db}
	srv := eventsource.NewServer()
	srv.Register("articles", repo)
	channels := make(map[string]struct{})
	var lock sync.Mutex
	router := mux.NewRouter().StrictSlash(false)
	router.HandleFunc("/", srv.Handler("articles"))
	router.HandleFunc("/{channel}/", func(resp http.ResponseWriter, req *http.Request) {
		channel := mux.Vars(req)["channel"]
		lock.Lock()
		if _, ok := channels[channel]; !ok {
			channels[channel] = struct{}{}
			srv.Register(channel, repo)
		}
		lock.Unlock()
		srv.Handler(mux.Vars(req)["channel"])(resp, req)
	})
	http.Handle("/", router)
	l, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
	if err != nil {
		glog.Fatal(err)
	}
	defer l.Close()
	glog.Infof("Listening on port %d", *port)
	go repo.Monitor(srv)
	http.Serve(l, nil)
}
コード例 #7
0
func newFakeMarathonEndpoint(t *testing.T, configs *configContainer) *endpoint {
	// step: read in the fake responses if required
	initFakeMarathonResponses(t)

	// step: create a fake SSE event service
	eventSrv := eventsource.NewServer()

	// step: fill in the default if required
	defaultConfig := NewDefaultConfig()
	if configs == nil {
		configs = &configContainer{}
	}
	if configs.client == nil {
		configs.client = &defaultConfig
	}
	if configs.server == nil {
		configs.server = &serverConfig{}
	}

	fakeRespIndices := map[string]int{}

	// step: create the HTTP router
	mux := http.NewServeMux()
	mux.HandleFunc("/v2/events", authMiddleware(configs.server, eventSrv.Handler("event")))
	mux.HandleFunc("/", authMiddleware(configs.server, func(writer http.ResponseWriter, reader *http.Request) {
		respKey := fakeResponseMapKey(reader.Method, reader.RequestURI, configs.server.scope)
		fakeRespIndex := fakeRespIndices[respKey]
		fakeRespIndices[respKey]++
		responses, found := fakeResponses[respKey]
		if found {
			for _, response := range responses {
				// Index < 0 indicates a static response.
				if response.Index < 0 || response.Index == fakeRespIndex {
					writer.Header().Add("Content-Type", "application/json")
					writer.Write([]byte(response.Content))
					return
				}
			}
		}

		http.Error(writer, `{"message": "not found"}`, 404)
	}))

	// step: create HTTP test server
	httpSrv := httptest.NewServer(mux)

	if configs.client.URL == defaultConfig.URL {
		configs.client.URL = getTestURL(httpSrv.URL)
	}

	// step: create the client for the service
	client, err := NewClient(*configs.client)
	if err != nil {
		t.Fatalf("Failed to create the fake client, %s, error: %s", configs.client.URL, err)
	}

	return &endpoint{
		Server: fakeServer{
			eventSrv:        eventSrv,
			httpSrv:         httpSrv,
			fakeRespIndices: fakeRespIndices,
		},
		Client: client,
		URL:    configs.client.URL,
	}
}
コード例 #8
0
ファイル: testing_utils.go プロジェクト: synack/go-marathon
func newFakeMarathonEndpoint(t *testing.T, config *Config) *endpoint {
	once.Do(func() {
		// step: open and read in the methods yaml
		contents, err := ioutil.ReadFile(fakeAPIFilename)
		if err != nil {
			t.Fatalf("unable to read in the methods yaml file: %s", fakeAPIFilename)
		}
		// step: unmarshal the yaml
		var methods []*restMethod
		err = yaml.Unmarshal([]byte(contents), &methods)
		if err != nil {
			t.Fatalf("Unable to unmarshal the methods yaml, error: %s", err)
		}

		// step: construct a hash from the methods
		uris = make(map[string]*string, 0)
		for _, method := range methods {
			uris[fmt.Sprintf("%s:%s", method.Method, method.URI)] = &method.Content
		}
	})

	eventSrv := eventsource.NewServer()

	mux := http.NewServeMux()
	mux.HandleFunc("/v2/events", eventSrv.Handler("event"))
	mux.HandleFunc("/", func(writer http.ResponseWriter, reader *http.Request) {
		key := fmt.Sprintf("%s:%s", reader.Method, reader.RequestURI)
		content, found := uris[key]
		if found {
			writer.Header().Add("Content-Type", "application/json")
			writer.Write([]byte(*content))
			return
		}

		http.Error(writer, "not found", 404)
	})

	httpSrv := httptest.NewServer(mux)

	defaultConfig := NewDefaultConfig()
	if config == nil {
		config = &defaultConfig
	}

	if config.URL == defaultConfig.URL {
		config.URL = getTestURL(httpSrv.URL)
	}

	client, err := NewClient(*config)
	if err != nil {
		t.Fatalf("Failed to create the fake client, %s, error: %s", config.URL, err)
	}

	return &endpoint{
		Server: fakeServer{
			eventSrv: eventSrv,
			httpSrv:  httpSrv,
		},
		Client: client,
		URL:    config.URL,
	}
}