Example #1
0
func setupEventSource(rediscommand_ch <-chan redis_protocol.RedisCommand) {
	es := eventsource.New(nil, nil)
	defer es.Close()
	go notifyClients(rediscommand_ch, es)
	http.Handle("/redis", es)
	http.Handle("/", http.FileServer(http.Dir("./ui/dist")))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
Example #2
0
func newEventSource(evm event.EventManager) eventsource.EventSource {
	es := eventsource.New(nil, nil)

	var id int = -1
	evm.Bind(event.AllEvents, func(es eventsource.EventSource, ev event.Event) {
		id++
		data, _ := json.Marshal(ev.Data)
		go es.SendEventMessage(string(data), string(ev.Type), strconv.Itoa(id))
	})

	return es
}
Example #3
0
func main() {
	var (
		ClientID     = flag.String("i", "", "OAuth2 Client ID")
		ClientSecret = flag.String("s", "", "OAtuh2 Client Secret")
		Redis        = flag.String("r", "", "Redis Connection String")
		err          error
	)
	flag.Parse()

	if *Redis != "" {
		// First, open a redis connection we use for stats
		if connectToRedis(*Redis) != nil {
			return
		}

		// Now start the eventsource loop for client-side stat update
		es = eventsource.New(nil, nil)
		defer es.Close()
		go broadcastLoop()
	}

	// Load the HTML static page
	data, err := ioutil.ReadFile("templates/index.html")
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Error("Failed to open index.html")
		return
	}
	htmlIndexPage = string(data)

	// Create a cookie store
	store = sessions.NewCookieStore([]byte(*ClientSecret))

	// Setup the OAuth2 Configuration
	endpoint := oauth2.Endpoint{
		AuthURL:  apiBaseUrl + "/oauth2/authorize",
		TokenURL: apiBaseUrl + "/oauth2/token",
	}

	oauthConf = &oauth2.Config{
		ClientID:     *ClientID,
		ClientSecret: *ClientSecret,
		Scopes:       []string{"bot", "identify"},
		Endpoint:     endpoint,
		RedirectURL:  "https://airhornbot.com/callback",
	}

	server()
}
Example #4
0
File: main.go Project: hhatto/ftcat
func execCmd(c *cli.Context) {
	if len(c.Args()) < 1 {
		fmt.Println("Specify Markdown file")
		return
	}

	/* open webbrowser */
	open.Start("http://0.0.0.0:8089")

	ch := make(chan string)
	gChan = make(chan string)

	targetFileName = c.Args()[0]
	go fileWatcher(ch)

	/* for static files */
	staticFilePath := path.Join(os.Getenv("GOPATH"), "src/github.com/hhatto/ftcat/static")
	fs := http.FileServer(http.Dir(staticFilePath))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	/* index */
	http.HandleFunc("/", indexHandler)

	/* server sent events */
	es := eventsource.New(nil, nil)
	defer es.Close()
	http.Handle("/events", es)

	/* message broker */
	go func() {
		id := 1
		for {
			select {
			case n := <-ch:
				es.SendEventMessage(n, "cre", strconv.Itoa(id))
				id++
			case n := <-gChan:
				es.SendEventMessage(n, "cre", strconv.Itoa(id))
				id++
			}
		}
	}()

	log.Fatal(http.ListenAndServe(":8089", nil))
}
Example #5
0
func main() {
	hostCache = make(map[string]string)
	es := eventsource.New(nil, nil)
	defer es.Close()

	http.Handle("/events", es)
	go ClockSource(es)
	go MulticastListener(es)

	// Serve static files
	// http.Handle("/", autogzip.Handle(http.FileServer(http.Dir(staticPath))))
	http.Handle("/", http.FileServer(http.Dir(staticPath)))

	err := http.ListenAndServe(fmt.Sprintf(":%d", listenPort), handlers.CombinedLoggingHandler(os.Stdout, http.DefaultServeMux))
	if err != nil {
		log.Fatal(err)
	}
}
Example #6
0
func main() {
	var (
		settingsPath = flag.String("settings", "./settings.toml", "")
		port         = flag.String("port", "8080", "")
		socket       = flag.String("socket", "", "")
	)
	flag.Parse()

	var conf *Conf
	if _, err := toml.DecodeFile(*settingsPath, &conf); err != nil {
		log.Fatal("toml:", err)
	}

	db := database.Open(conf.DbPath, conf.Horizon)
	defer db.Close()

	es := eventsource.New(nil, nil)
	defer es.Close()

	store := uberich.NewStore(conf.Secret)
	uberich := uberich.NewClient(conf.Uberich.AppName, conf.Uberich.AppURL, conf.Uberich.UberichURL, conf.Uberich.Secret, store)

	shield := func(h http.Handler) http.Handler {
		return uberich.Protect(h, http.NotFoundHandler())
	}

	http.Handle("/", uberich.Protect(List(conf, db, true), List(conf, db, false)))
	http.Handle("/add", shield(Add(conf, db, es)))
	http.Handle("/preview", shield(Preview))
	http.Handle("/feed", Feed(conf, db))
	http.Handle("/connect", es)

	http.Handle("/sign-in", uberich.SignIn("/"))
	http.Handle("/sign-out", uberich.SignOut("/"))

	http.Handle("/assets/", http.StripPrefix("/assets/", assets.Server(map[string]string{
		"jquery.caret.js":        assets.Caret,
		"jquery.autosize.min.js": assets.AutoSize,
		"styles.css":             assets.Styles,
		"list.js":                assets.List,
	})))

	serve.Serve(*port, *socket, Log(http.DefaultServeMux))
}
Example #7
0
File: js.go Project: axet/terminal
func (m *Js) Handler(w http.ResponseWriter, r *http.Request) {
	pp := strings.Split(r.URL.Path, "/")

	// /js/events
	//
	// pp[0] == ""
	// pp[1] == "js"
	// pp[2] == "events"

	pp = pp[2:]

	switch pp[0] {
	case "events":
		if len(pp) > 1 {
			id := pp[1]
			es, t := m.es[id]
			if !t {
				fmt.Fprintln(w, "bad es channel id", id)
				return
			}
			es.ServeHTTP(w, r)
		} else {
			id, err := core.UUID()
			if err != nil {
				fmt.Fprintln(w, err)
				return
			}

			// TODO add timeout clean up's for disconnected es objects
			// js client may disconnect and reconnect to current object.
			// objects not accessed for few minutes may be marked as dead and purged from
			// m.es list
			m.es[id] = eventsource.New(nil, nil)
			fmt.Fprintln(w, id)

			// js unable to handle redirects :(
			//
			// http.Redirect(w, r, "/js/events/" + id, http.StatusMovedPermanently)
			return
		}
	case "rpc":
		body, _ := ioutil.ReadAll(r.Body)

		var mm map[string]*json.RawMessage
		err := json.Unmarshal(body, &mm)
		if err != nil {
			fmt.Fprintln(w, err)
			return
		}

		for key, value := range mm {
			switch key {
			case "system":
				// ignore
			case "core":
				var c RPCCore
				err = json.Unmarshal(*value, &c)
				if err != nil {
					fmt.Fprintln(w, err)
					return
				}
				switch c.Method {
				case "app":
					_, ok := core.Apps[c.Name]
					if ok {
						fmt.Fprintln(w, "OK")
						return
					} else {
						fmt.Fprintln(w, "App does not exist", c.Name)
						return
					}
				case "devices_uuid":
					d, ok := core.Devices[c.Name]
					if ok {
						t := strings.Trim(path.Ext(reflect.TypeOf(d).String()), ".")
						fmt.Fprintln(w, "{ \"type\" : \""+t+"\", \"uuid\" : \""+c.Name+"\" }")
						return
					} else {
						fmt.Fprintln(w, "Device does not exist", c.Name)
						return
					}
				case "devices_type":
					dt, t := core.TypesMap[c.Name]
					if !t {
						fmt.Fprintln(w, "Device type does not exist", c.Name)
						return
					}
					var buf string
					for k, v := range core.Devices {
						t := reflect.TypeOf(v).Implements(dt)
						if t {
							buf += "\"" + k + "\","
						}
					}
					buf = strings.TrimRight(buf, ",")
					fmt.Fprintln(w, "["+buf+"]")
					return
				case "service":
					_, ok := core.Services[c.Name]
					if ok {
						fmt.Fprintln(w, "OK")
						return
					} else {
						fmt.Fprintln(w, "Service does not exist", c.Name)
						return
					}
				default:
					fmt.Fprintln(w, "bad method:", c.Method)
					return
				}
			case "service":
				r, err := m.Js2Go(core.Services, value)
				if err != nil {
					fmt.Fprintln(w, err)
					return
				}
				fmt.Fprintln(w, r)
				return
			case "device":
				r, err := m.Js2Go(core.Devices, value)
				if err != nil {
					fmt.Fprintln(w, err)
					return
				}
				fmt.Fprintln(w, r)
				return
			default:
				fmt.Fprintln(w, "bad key:", key)
				return
			}
		}
	case "js.js":
		buf, err := ioutil.ReadFile(core.Res() + "/js.js")
		if err != nil {
			fmt.Fprintln(w, err)
			return
		}
		fmt.Fprintln(w, string(buf))
		return
	default:
		if val, ok := m.htmlapps[path.Join(pp...)]; ok {
			buf, err := ioutil.ReadFile(val)
			if err != nil {
				fmt.Fprintln(w, "bad js app", err)
				return
			}
			fmt.Fprintln(w, string(buf[:]))
			return
		} else {
			fmt.Fprintln(w, "bad js app path", pp[0])
			return
		}
	}
}
Example #8
0
func New() *Source {
	return &Source{eventsource.New(nil, nil)}
}