Exemplo n.º 1
0
func init() {
	var err error
	session, err = gorethink.Connect(gorethink.ConnectOpts{
		Address: "127.0.0.1:28015",
	})
	if err != nil {
		panic(err)
	}

	key2find = uniuri.New()

	// Create a new table
	gorethink.Db("test").TableDrop("benchmark_keys_list").Run(session)
	gorethink.Db("test").TableCreate("benchmark_keys_list").Run(session)

	var klist []*KeysList

	// Populate with sample data
	for n := 0; n < 300; n++ {
		keys := rndStringSlice(999)
		keys = randomlyInsert(keys, key2find)

		y := uniuri.New()
		if n == 153 {
			table2search = y
		}

		klist = append(klist, &KeysList{
			ID:    y,
			Voted: keys,
		})
	}

	gorethink.Db("test").Table("benchmark_keys_list").Insert(klist).Run(session)
}
Exemplo n.º 2
0
func (s *Service) HandleHit(w http.ResponseWriter, req *http.Request) error {
	h, e := NewHitFromRequest(req)
	if e != nil {
		return e
	}
	if ok, e := s.Store.HasSite(h.Host); !ok {
		if e != nil {
			return e
		}
		return ErrUnknownSite
	}
	if h.Ssid == "new" {
		h.Ssid = uniuri.New()
		newCookie := &http.Cookie{Name: SsidCookieName, Value: h.Ssid}
		http.SetCookie(w, newCookie)
	}
	if h.Uid == "new" {
		h.Uid = uniuri.New()
		now := time.Now()
		newCookie := &http.Cookie{Name: UidCookieName, Value: h.Uid, MaxAge: UidCookieMaxAge, Expires: now.Add(time.Duration(UidCookieMaxAge))}
		http.SetCookie(w, newCookie)
	}

	h.SetStore(s.Store)
	go s.Save(h)
	return nil
}
Exemplo n.º 3
0
func (h *GameHub) createRoom(gameType string, playerId string) {
	r := &GameRoom{roomId: uniuri.New()}
	// Add room to game hub
	h.rooms[r.roomId] = r
	// Move calling player to that room
	r.players[playerId] = true
}
Exemplo n.º 4
0
func generateRandomFilename(contentType string) string {
	filename := uniuri.New()
	if contentType == "image/png" {
		return filename + ".png"
	}
	return filename + ".jpg"
}
Exemplo n.º 5
0
func generateSHA1(parent string) (id string, err error) {
	id = ""

	usr, err := user.Current()
	if err != nil {
		return
	}

	// add entropy
	s := uniuri.New()

	// maybe s would be enough, but just in case, we add more
	payload := parent + s + usr.Uid + usr.Gid + usr.Username + usr.Name + usr.HomeDir

	h := sha1.New()

	if cnt, err := io.WriteString(h, payload); cnt != len(payload) {
		return "", KinIDGenerationError{"can't write payload for SHA1"}
	} else if err != nil {
		return "", err
	}

	id = hex.EncodeToString(h.Sum(nil))

	return
}
Exemplo n.º 6
0
func rndStringSlice(count int) []string {
	var r []string
	for i := 0; i < count; i++ {
		r = append(r, uniuri.New())
	}
	return r
}
Exemplo n.º 7
0
func (suite *StoreImplTest) TestLinkFailures(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{TableName: tableName, DB: db}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	v := AccountT{
		ID:                  "12345",
		Name:                "alice",
		Email:               "*****@*****.**",
		UnmarshalFailPlease: true,
	}
	err = s.Put([]string{"Accounts", "12345"}, &v)
	c.Assert(err, IsNil)

	err = s.PutLink([]string{"AccountsByEmail", "*****@*****.**"}, []string{"Accounts", "12345"})
	c.Assert(err, IsNil)

	_, err = s.GetLink([]string{"AccountsByEmail", "missing"})
	c.Assert(err, Equals, ErrNotFound)

	_, err = s.GetLink([]string{"Accounts", "12345"})
	c.Assert(err, Equals, ErrNotLink)
}
Exemplo n.º 8
0
func (suite *StoreImplTest) TestLongPath(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{TableName: tableName, DB: db}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	v := AccountT{
		ID:                  "12345",
		Name:                "alice",
		Email:               "*****@*****.**",
		UnmarshalFailPlease: true,
	}
	key := []string{}
	for i := 0; i < 50; i++ {
		key = append(key, "X")
	}
	err = s.Put(key, &v)
	c.Assert(err, IsNil)

	key2 := []string{}
	for i := 0; i < 50; i++ {
		key2 = append(key2, "L")
	}
	err = s.PutLink(key2, []string{"foo"})
	c.Assert(err, IsNil)

	err = s.Delete(key)
	c.Assert(err, IsNil)
	err = s.Delete(key2)
	c.Assert(err, IsNil)
}
Exemplo n.º 9
0
func (c *Client) Request(method, path string, headers map[string]string, body interface{}) ([]string, string, error) {
	if headers == nil {
		headers = map[string]string{}
	}

	if c.Headers != nil {
		for k, v := range c.Headers {
			headers[k] = v
		}
	}

	req := &Request{
		ID:      uniuri.New(),
		Type:    "request",
		Path:    path,
		Method:  method,
		Headers: headers,
	}

	if body != nil {
		data, err := json.Marshal(body)
		if err != nil {
			return nil, "", err
		}

		req.Body = string(data)
	}

	d, err := Encode(req)
	if err != nil {
		return nil, "", err
	}

	return d, req.ID, nil
}
Exemplo n.º 10
0
// Take n tokens from bucket t, key k
func (client *Client) Take(t string, k string, n int32) (response *limitd.Response, takeResponse *limitd.TakeResponse, err error) {
	requestID := uniuri.New()

	request := &limitd.Request{
		Id:     proto.String(requestID),
		Method: limitd.Request_TAKE.Enum(),
		Type:   proto.String(t),
		Key:    proto.String(k),
		Count:  proto.Int32(n),
	}

	// goprotobuf.EncodeVarint followed by proto.Marshal
	responseChan := make(chan *limitd.Response)
	client.PendingRequests[requestID] = responseChan

	data, _ := proto.Marshal(request)
	data = append(proto.EncodeVarint(uint64(len(data))), data...)
	client.Conn.Write(data)

	response = <-responseChan
	takeR, err := proto.GetExtension(response, limitd.E_TakeResponse_Response)
	if err != nil {
		return
	}

	if takeResponseCasted, ok := takeR.(*limitd.TakeResponse); ok {
		takeResponse = takeResponseCasted
	}

	return
}
Exemplo n.º 11
0
// NewEtcdGlobalMutexService returns a global mutex service implementation
// based on ETCD.
func NewEtcdGlobalMutexService(etcdClient client.Client, prefix string) GlobalMutexService {
	return &etcdGlobalMutexService{
		etcdClient: etcdClient,
		prefix:     prefix,
		ownerID:    uniuri.New(),
	}
}
Exemplo n.º 12
0
func (suite *StoreImplTest) TestReservedCharacters(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{
		TableName:        tableName,
		DB:               db,
		SpecialCharacter: "X",
	}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	v := AccountT{
		ID:    "12345",
		Name:  "alice",
		Email: "*****@*****.**",
	}
	err = s.Put([]string{"Accounts", "12X345"}, &v)
	c.Assert(err, Equals, ErrReservedCharacterInKey)

	v.Xfoo = "cannot be set"
	err = s.Put([]string{"Accounts", "12345"}, &v)
	c.Assert(err, Equals, ErrReservedCharacterInAttribute)

	v.Xfoo = ""
	v.FooXBar = "can be set"
	err = s.Put([]string{"Accounts", "12345"}, &v)
	c.Assert(err, IsNil)

	err = s.PutLink([]string{"AccountsXEmail", "*****@*****.**"}, []string{"Accounts", "12345"})
	c.Assert(err, Equals, ErrReservedCharacterInKey)

	err = s.PutLink([]string{"AccountsByEmail", "*****@*****.**"}, []string{"AccountsX", "12345"})
	c.Assert(err, Equals, ErrReservedCharacterInKey)
}
Exemplo n.º 13
0
func (d *dockerMock) CreateContainer(docker.CreateContainerOptions) (*docker.Container, error) {
	container := &docker.Container{
		ID: uniuri.New(),
	}
	d.containers = append(d.containers, container)
	return container, nil
}
Exemplo n.º 14
0
// AddTodo appends a new todo to the list.
func (list *TodoList) AddTodo(title string) {
	list.todos = append(list.todos, &Todo{
		id:    uniuri.New(),
		title: title,
		list:  list,
	})
	list.changed()
}
Exemplo n.º 15
0
func (lw *LocalWorker) Start(taskType string, wg *sync.WaitGroup, reqChan chan int64, resChan chan *common.Result) error {
	lw.reqChan = reqChan
	lw.resChan = resChan
	lw.wg = wg
	lw.wg.Add(1)
	go lw.runWorker(taskType, uniuri.New())

	return nil
}
Exemplo n.º 16
0
func Add() (object *Object, err error) {
	object = &Object{}
	object.ObjectId = uniuri.New()
	object.Score = 0
	object.Lives = 5
	object.Completed = []string{}

	err = Set(object)
	return object, err
}
Exemplo n.º 17
0
// CreateLink handles requests to create links
func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) {
	account := r.Header.Get("X-Remote-User")
	l := Link{
		ShortLink: uniuri.New(),
		Target:    r.FormValue("t"),
		Owner:     account,
	}
	links[l.ShortLink] = l

	fmt.Fprintf(w, "%s\n", l.ShortLink)
	return
}
Exemplo n.º 18
0
func (suite *StoreImplTest) TestDoubleCreate(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{TableName: tableName, DB: db}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	// Create the table again. The create fails because the table exists, which is
	// what we expect.
	err = s.CreateTable()
	c.Assert(err, IsNil)
}
Exemplo n.º 19
0
func wsHandler(ws *websocket.Conn) {
	player := &Player{id: uniuri.New(), conn: &connection{send: make(chan string, 256), ws: ws}}
	gamehub.register <- player
	gamehub.broadcast <- player.AnnouncePlayer("Lobby", false)
	player.SendPlayerIdentity()
	defer func() {
		gamehub.unregister <- player
		gamehub.broadcast <- player.AnnouncePlayer("", true)
	}()
	go player.conn.writer()
	player.conn.reader()
}
Exemplo n.º 20
0
func NewXHR(address string) (*XHR, error) {
	xhr := &XHR{
		Address:   address,
		ServerID:  paddedRandomIntn(999),
		SessionID: uniuri.New(),
	}
	xhr.TransportAddress = address + "/" + xhr.ServerID + "/" + xhr.SessionID
	if err := xhr.Init(); err != nil {
		return nil, err
	}
	xhr.StartReading()

	return xhr, nil
}
Exemplo n.º 21
0
func NewWebSocket(address string) (*WebSocket, error) {
	ws := &WebSocket{
		Address:     address,
		ServerID:    paddedRandomIntn(999),
		SessionID:   uniuri.New(),
		Inbound:     make(chan []byte),
		Reconnected: make(chan struct{}, 32),
	}

	ws.TransportAddress = address + "/" + ws.ServerID + "/" + ws.SessionID + "/websocket"

	ws.Loop()

	return ws, nil
}
Exemplo n.º 22
0
func (suite *StoreImplTest) TestMarshalFails(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{TableName: tableName, DB: db}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	v := AccountT{
		ID:                "12345",
		Name:              "alice",
		Email:             "*****@*****.**",
		MarshalFailPlease: true,
	}
	_ = s.Put([]string{"Accounts", "12345"}, &v)
	//c.Assert(err, ErrorMatches, "could not grob the frob")
}
Exemplo n.º 23
0
func NewTestArticle(t *testing.T, a *Article) *Article {
	if a == nil {
		a = &Article{
			IsDeleted:   false,
			IsPublished: true,
		}
	}

	if a.Title == "" {
		a.Title = uniuri.New()
	}

	if err := a.Save(); err != nil {
		t.Fatalf("failed to save article: %s", err)
	}
	return a
}
Exemplo n.º 24
0
func generateRandomFilename(contentType string) string {

	var ext string

	switch contentType {
	case "image/jpeg":

		ext = ".jpg"
	case "image/png":
		ext = ".png"

	case "image/gif":
		ext = ".gif"
	}

	return uniuri.New() + ext
}
Exemplo n.º 25
0
// CreateLink handles requests to create links
func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) {
	account := GetAccount(c)
	l := Link{
		ShortLink: uniuri.New(),
		Target:    r.FormValue("t"),
	}
	if err := tree.Put([]string{"Links", l.ShortLink}, &l); err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if err := tree.PutLink([]string{"Accounts", account.Email, "Links", l.ShortLink},
		[]string{"Links", l.ShortLink}); err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "%s\n", l.ShortLink)
	return
}
Exemplo n.º 26
0
func indexPage(ctx *web.Context) {
	updateRemoteAddr(ctx)

	tmpl, err := template.New("index").Parse(indexTemplate)

	if err != nil {
		panic(err)
	}

	key := uniuri.New()
	v := IndexTemplateValue{appConfig, key}

	if ctx.Request.Host != "" {
		v.Host = ctx.Request.Host
	}
	if v.Scheme == "" {
		v.Scheme = appConfig.BindScheme
	}
	tmpl.Execute(ctx, v)
}
Exemplo n.º 27
0
func (ctrl FoodController) Create(r render.Render, params martini.Params, req *http.Request) {

	var payload Food

	// this application only accepts json posting
	hasJson := req.Header.Get("Content-Type") == "application/json"

	// not using JSON, bad request
	if !hasJson {
		r.JSON(http.StatusBadRequest, ErrJson(http.StatusBadRequest))
		return
	}

	// parse the json data
	data, readErr := ioutil.ReadAll(req.Body)
	jsonErr := json.Unmarshal(data, &payload)

	// let the user know if there was an error
	if readErr != nil || jsonErr != nil {
		r.JSON(http.StatusInternalServerError, ErrJson(http.StatusInternalServerError))
		return
	}

	if payload.Name == "" || payload.Family == "" {
		// missing feilds from POST request
		r.JSON(http.StatusBadRequest, ErrJson(http.StatusBadRequest))
		return
	}

	// use uniuri to gen a random id
	payload.FoodId = uniuri.New()

	// add to dirty storage
	foods[payload.Name] = payload

	// spit out the new food with a create status code
	r.JSON(http.StatusCreated, payload)
	return
}
Exemplo n.º 28
0
func (b *Builder) createContainer(step *Step) (*docker.Container, error) {
	config := docker.Config{
		AttachStdout: true,
		AttachStdin:  false,
		AttachStderr: true,
		Image:        b.uniqueStepName(step),
		Cmd:          []string{"/bin/bash"},
		Tty:          true,
	}

	r, _ := regexp.Compile("/?[^a-zA-Z0-9_-]+")
	containerName := r.ReplaceAllString(b.uniqueStepName(step), "-") + "." + uniuri.New()
	opts := docker.CreateContainerOptions{
		Name:   containerName,
		Config: &config,
	}
	container, err := b.docker.CreateContainer(opts)
	if err != nil {
		return nil, err
	}

	return container, nil
}
Exemplo n.º 29
0
func NewKurafuto(config *Config) (ku *Kurafuto, err error) {
	if len(config.Servers) < 1 {
		err = errors.New("kurafuto: Need at least 1 server in config.")
		return
	}

	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", config.Address, config.Port))
	if err != nil {
		return
	}

	ku = &Kurafuto{
		Players:  []*Player{},
		mutex:    sync.Mutex{},
		salt:     uniuri.New(),
		Hub:      &config.Servers[0],
		Config:   config,
		Listener: listener,
		Done:     make(chan bool, 1),

		rMut: sync.Mutex{},
	}
	return
}
Exemplo n.º 30
0
func (suite *StoreImplTest) TestListAbort(c *C) {
	tableName := uniuri.New()
	db := dynamodb.New(session.New(), fakeDynamodbServer.Config)
	s := &Tree{TableName: tableName, DB: db}
	err := s.CreateTable()
	c.Assert(err, IsNil)

	v := AccountT{
		ID:                  "12345",
		Name:                "alice",
		Email:               "*****@*****.**",
		UnmarshalFailPlease: true,
	}
	err = s.Put([]string{"Accounts", "12345"}, &v)
	c.Assert(err, IsNil)
	err = s.Put([]string{"Accounts", "6789"}, &v)
	c.Assert(err, IsNil)

	s.List([]string{"Accounts"}, func(item string, err error) bool {
		c.Assert(err, IsNil)
		c.Assert(item, Equals, "12345")
		return false
	})
}