示例#1
0
func GetKey(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	service := vars["service"]

	for k, v := range limits {
		if k != service {
			continue
		}
		for ck, l := range v {
			// Have more then 0 attempts or refresh time is reached
			if l.Remaining > 0 || time.Now().UTC().Unix() > l.Reset {

				// Send as JSON
				w.Header().Set("Content-Type", "application/json; charset=UTF-8")
				w.WriteHeader(http.StatusOK)
				err := json.NewEncoder(w).Encode(l.Key)
				check_err(err)

				// Delete from storage
				delete(limits[service], ck)

				refresh_str := go_strftime.Strftime("%Y-%m-%d %H:%M:%S UTC", time.Unix(l.Reset, 0).UTC())
				log.Printf("GET key \"%s\" for service %s, remaining: %d, reset: %s, bullets: %d", ck, service, l.Remaining, refresh_str, len(limits[service]))
				return
			}
		}
	}

	// No one suitable key
	w.WriteHeader(http.StatusNoContent)
}
示例#2
0
func SetKey(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	service := vars["service"]

	// Pass only our keys
	for _, s := range services {
		if s == service {
			break
		}
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// Read data from requested form
	consumer_key := r.FormValue("consumer_key")
	consumer_secret := r.FormValue("consumer_secret")
	access_token := r.FormValue("access_token")
	access_token_secret := r.FormValue("access_token_secret")

	// Make key
	key := Key{
		ConsumerKey: consumer_key, ConsumerSecret: consumer_secret,
		AccessToken: access_token, AccessTokenSecret: access_token_secret,
	}

	// Check key
	if _, ok := keys_hash[key.Hash()]; !ok {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, "Have no key inside keys dictionary")
		return
	}

	// Read optional field "remaining"
	remaining, err := strconv.ParseInt(r.FormValue("remaining"), 10, 64)
	if err != nil {
		remaining = 1
	}

	// Read optional field "reset"
	reset, err := strconv.ParseInt(r.FormValue("reset"), 10, 64)
	if err != nil {
		reset = time.Now().UTC().Unix()
	}

	// App key to storage
	limits[service][key.ConsumerKey] = Limits{Remaining: remaining, Reset: reset, Key: key}

	refresh_str := go_strftime.Strftime("%Y-%m-%d %H:%M:%S UTC", time.Unix(reset, 0).UTC())
	log.Printf("SET key \"%s\" for service \"%s\", remaining: %d, reset: %s, bullets: %d", key.ConsumerKey, service, remaining, refresh_str, len(limits[service]))

	w.WriteHeader(http.StatusOK)
}