Пример #1
0
func Wait() {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, os.Interrupt)
	llog.Warn(`Check watch. Enter ctrl+c to continue`)
	<-sigs
	signal.Stop(sigs)
	llog.Warn(`Test continues`)
}
Пример #2
0
func main() {
	options := cfg.GetOptions()

	log.Info("Server is ready!", "port", options.Port, "token", options.Token)
	log.Info(fmt.Sprintf("Listening for post requests on http://localhost:%s/events", options.Port))
	log.Info(fmt.Sprintf("SSE streaming avaliable on http://localhost:%s/stream", options.Port))

	es := eventsource.New(
		eventsource.DefaultSettings(),
		func(req *http.Request) [][]byte {
			return [][]byte{
				[]byte("X-Accel-Buffering: no"),
				[]byte("Access-Control-Allow-Origin: *"),
				[]byte("Cache-Control: no-cache"),
			}
		},
	)

	defer es.Close()

	r := mux.NewRouter()

	r.Handle("/stream", es)

	r.HandleFunc("/event/{event}/{id}", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			if token, ok := r.Header["X-Token"]; ok {
				if token[0] == options.Token {
					event := mux.Vars(r)["event"]
					id := mux.Vars(r)["id"]

					data, err := ioutil.ReadAll(r.Body)
					if err != nil {
						log.Error("Cannot read body", "err", err)
					}

					es.SendEventMessage(string(data), event, id)
					log.Info("Message has been sent", "id", id, "event", event)

				} else {
					log.Warn("The request has wrong token", "token", token[0])
					http.Error(w, "The request has wrong token", http.StatusUnauthorized)
				}
			} else {
				log.Warn("The request doesn't contain authentication token")
				http.Error(w, "The request doesn't contain authentication token", http.StatusUnauthorized)
			}
		} else {
			log.Warn("Received wrong http request")
			http.Error(w, "POST requests only", http.StatusMethodNotAllowed)
		}
	})

	r.Handle("/", http.FileServer(http.Dir("./public")))
	http.ListenAndServe(fmt.Sprintf(":%s", options.Port), r)
}
Пример #3
0
// doPost posts a notification to a channel. If it is full, doPost will drop the
// notification and print a log warning.
func (n *Notifier) doPost(nchan chan interface{}, val interface{}) {
	if n == nil {
		return
	}
	if lock, ok := n.channelLocks[nchan]; ok {
		lock.Lock()
		if len(nchan) < cap(nchan) {
			n.log.Debug("posting notification to channel", "chan", nchan, "value", val)
			nchan <- val
		} else {
			log.Warn("dropping notification to channel because it is full", "chan", nchan)
		}
		lock.Unlock()
	} else {
		log.Warn("dropping notification to channel because a matching channel lock was not found", "chan", nchan)
	}
}
Пример #4
0
func getWeather(apiURL string) interface{} {
	var weatherBody interface{}

	resp, err := http.Get(apiURL)
	if err != nil {
		log.Warn("Failed to fetch weather", "error", err.Error())
	}
	defer resp.Body.Close()

	decoder := json.NewDecoder(resp.Body)

	err = decoder.Decode(&weatherBody)
	if err != nil {
		log.Warn("Failed to parse weather body", "error", err.Error())
	}

	return weatherBody
}
Пример #5
0
func userRoutine(u User, c chan<- interface{}) error {

	ts := tokenSource{
		&oauth2.Token{
			AccessToken: u.AccessToken,
		},
	}

	tc := oauth2.NewClient(oauth2.NoContext, ts)

	client := github.NewClient(tc)

	//List Options Page, PerPage
	opts := github.ListOptions{1, 1}

	for {
		events, resp, err := client.Activity.ListEventsPerformedByUser(u.Username, false, &opts)
		if err != nil {
			log.Warn("Problem retrieving events for user", "username", u.Username, "error", err.Error())
		}

		newEventTime := LastEvent.EventTime

		if len(events) > 0 {
			newEventTime = *events[0].CreatedAt
		}

		// read in last event and compare to new event time
		LastEvent.Lock()
		dur := LastEvent.EventTime.Sub(newEventTime)
		if dur.Seconds() > 0.0 {
			LastEvent.EventTime = newEventTime
			c <- events[0]
		}
		LastEvent.Unlock()

		// Wait as long as the X-Poll-Interval header says to
		interval, err := strconv.ParseInt(resp.Header["X-Poll-Interval"][0], 10, 8)
		if err != nil {
			// if strconv failed for whatever reason, use the default X-Poll-Interval value of 60
			time.Sleep(60 * time.Second)
		} else {
			time.Sleep(time.Duration(interval) * time.Second)
		}
	}

	panic("Shouldn't be here")
}
Пример #6
0
func AddPodcast(w http.ResponseWriter, r *http.Request) {
	uploadedFile, err := uploadPodcast(r)
	if err != nil {
		log.Warn("error uploading/saving podcast", "message", err)
		uploadedFile.Failed = true
	} else {
		log.Info("file succesfully uploaded", "filename", uploadedFile.Name, "size", humanize.Bytes(uint64(uploadedFile.Size)))
	}

	renderObject := map[string]interface{}{
		"IsConfirmationPage": "true",
		"failed":             uploadedFile.Failed,
		"name":               uploadedFile.Name,
		"size":               uploadedFile.Size,
	}
	displayPage(w, r, renderObject)
}