示例#1
0
func incrCount(tde *kv.TiedotEngine) int64 {
	mu.Lock()
	defer mu.Unlock()
	counter := new(Counter)
	id, err := tde.Query(counterCollection).Has(kv.Path{"Count"}).OneInto(counter)
	if err == kv.ErrNotFound {
		log.Warning("Counter not found, saving new one.")
		_, err = tde.Insert(counterCollection, Counter{Count: 1})
		if err != nil {
			log.Errorf("Error saving new counter err=%s", err.Error())
		}
		r, err := tde.All(counterCollection)
		log.V(3).Infof("total of %d results=%v, err=%v", len(r), r, err)
		return 1
	}
	if err != nil {
		log.Error("Failure getting counter err:" + err.Error())
		panic(err)
	}
	counter.Count++
	err = tde.Update(counterCollection, id, counter)
	if err != nil {
		log.Error("Failure updating counter err:" + err.Error())
		panic(err)
	}
	return counter.Count
}
示例#2
0
func newShort(w http.ResponseWriter, r *http.Request, tde *kv.TiedotEngine) {
	defer r.Body.Close()
	raw, err := ioutil.ReadAll(r.Body)
	log.FatalIfErr(err, "Failure reading request err:")
	var v M
	err = json.Unmarshal(raw, &v)
	log.FatalIfErr(err, "Failure decoding JSON json:"+string(raw)+" err:")
	if dest, ok := v["url"]; ok {
		count := incrCount(tde)
		shortSlug := base62.EncodeInt(count)
		parsed, err := url.Parse(dest.(string))
		if err != nil {
			log.Warning("Malformed URL:" + dest.(string) + " err:" + err.Error())
		}
		if parsed.Scheme == "" {
			dest = "http://" + dest.(string)
		}

		s := Shortened{
			Original: dest.(string),
			Short:    count,
		}

		err = saveShortened(s, tde)
		log.FatalIfErr(err, "Failure saving URL err:")
		out, _ := json.Marshal(map[string]interface{}{
			"Short":    s.Short,
			"Original": s.Original,
			"Full":     *base + shortSlug,
			"HitCount": s.HitCount,
		})
		w.Write(out)
	} else {
		log.Info("No url field included in JSON")
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("Require 'url' field in request JSON"))
	}
}