func conHandler(c net.Conn) {
	defer c.Close()
	fmt.Printf("[counterproxy] - Accept connect: %v\n", c)

	mc, err := libmemcached.Connect("localhost", "11211")
	if err != nil {
		fmt.Println(err)
		fmt.Printf("[counterproxy] - Connect Memcached Server failed!\n")
		return
	}
	defer libmemcached.Close(mc)

	var buf [512]byte
	rb := ringbuf.New(512)

	for {
		n, err := c.Read(buf[:])

		if err != nil {
			fmt.Println(err)
			if err == io.EOF {
				fmt.Printf("[counterproxy] - Client [%v] shutdown!\n", c)
			}
			break
		}

		_, err = rb.Write(buf[:], n)
		if err != nil {
			fmt.Println(err)
			break
		}

		packages, err := proto.Parse(rb)
		if err != nil && err != proto.ErrInComplete {
			fmt.Println(err)
			fmt.Printf("[counterproxy] - Close the connection: %v\n", c)
			return
		}

		for i := range packages {
			t := time.Now()
			tmstamp := fmt.Sprintf("%d%02d%02d%02d%02d%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
			out, err := incr(mc, packages[i].Key, packages[i].Val, tmstamp, EXPIRE_TIME)
			if err != nil {
				fmt.Println(err)
				fmt.Printf("[counterproxy] - Incr err!\n")
				return
			}

			_, err = c.Write([]byte(tmstamp + " " + out + "\r\n"))
			if err != nil {
				fmt.Println(err)
				fmt.Printf("[counterproxy] - Send response err!\n")
				return
			}
		}
	}
}
Beispiel #2
0
func TestParseInvalidPackage(t *testing.T) {
	rb := ringbuf.New(512)

	s := "incr key1 10\r\nincr1 key2 11\r\n"
	rb.Write([]byte(s), len(s))
	packages, err := Parse(rb)
	assert.AssertEquals(t, ErrInvalidPack, err)
	assert.AssertEquals(t, 1, len(packages))
}
Beispiel #3
0
func BenchmarkPackageParse(b *testing.B) {

	for i := 0; i < b.N; i++ {
		b.StopTimer()
		s := "incr key1 10\r\nincr1 key2 11\r\n"
		rb := ringbuf.New(64)
		rb.Write([]byte(s), len(s))
		b.StartTimer()
		Parse(rb)
	}
}
Beispiel #4
0
func TestParseInCompletePackage(t *testing.T) {
	rb := ringbuf.New(512)

	s := "incr key1 10\r\nincr key2"
	rb.Write([]byte(s), len(s))
	packages, err := Parse(rb)
	assert.AssertEquals(t, ErrInComplete, err)
	assert.AssertEquals(t, 1, len(packages))
	assert.AssertEquals(t, INCR, packages[0].Cmd)
	assert.AssertEquals(t, "key1", packages[0].Key)
	assert.AssertEquals(t, "10", packages[0].Val)

	s = " 11\r\n"
	rb.Write([]byte(s), len(s))
	packages, err = Parse(rb)
	assert.AssertEquals(t, nil, err)
	assert.AssertEquals(t, 1, len(packages))
	assert.AssertEquals(t, INCR, packages[0].Cmd)
	assert.AssertEquals(t, "key2", packages[0].Key)
	assert.AssertEquals(t, "11", packages[0].Val)
}
Beispiel #5
0
func TestParseEmtpyRingBuf(t *testing.T) {
	rb := ringbuf.New(512)
	packages, err := Parse(rb)
	assert.AssertEquals(t, nil, err)
	assert.AssertEquals(t, 0, len(packages))
}