예제 #1
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"))
	}
}
예제 #2
0
func main() {
	log.UseStderr(true)
	log.SetV(9)
	flag.Parse()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	r := martini.NewRouter()

	tde := kv.NewTiedotEngine("./tiedotdb", []string{"short.url", "short.counter"}, kv.KeepIfExist)
	tde.AddIndex("short.url", kv.Path{"Short"})
	tde.AddIndex("short.counter", kv.Path{"Count"})

	if *useShort {
		log.Info("Starting LWS.short")
		s := short.NewShortener(tde)
		r.Any("/s", stripper("/s"), s.ServeHTTP)
		r.Any("/s/.*", stripper("/s"), s.ServeHTTP)
	}

	m.Action(r.Handle)
	http.ListenAndServe(*port, m)
}
예제 #3
0
// Create a new LevelDBEngine with the given file and options
func NewTiedotEngine(directory string, collections []string, dropPref DropPreference) *TiedotEngine {
	db, err := tiedot.OpenDB(directory)
	log.FatalIfErr(err, "Failure opening tiedot basedir err:")
	for _, c := range collections {
		if _, ok := db.StrCol[c]; ok {
			log.V(4).Info("Collection %s already exists")
			if dropPref == DropIfExist {
				log.Info("Dropping collection %s due to dropIfExist option")
				err = db.Drop(c)
				log.FatalIfErr(err, "Failure dropping collection with name:%s err:", c)
				err = db.Create(c, 1) // partition DB for use by up to 1 goroutines at a time
				log.FatalIfErr(err, "Failure creating collection with name:%s err:", c)
			}
		} else {
			log.V(4).Info("Creating collection %s")
			err = db.Create(c, 1) // partition DB for use by up to 1 goroutines at a time
			log.FatalIfErr(err, "Failure creating collection with name:%s err:", c)
		}
	}
	tde := &TiedotEngine{
		tiedot: db,
	}
	return tde
}