func main() { addr, err := net.ResolveTCPAddr("127.0.0.1:4009") if err != nil { log.Exit("error:", err) } listener, err := net.ListenTCP("tcp", addr) if err != nil { log.Exit("error", err) } //1 channel for incoming connections, another for client communication connections := make(chan *net.TCPConn) clients := make(chan TClient) cMap := make(map[string]*net.TCPConn) fMap := make(map[string]string) go ListenConnections(listener, connections, clients) log.Stdout("Waiting for connections\n") for { select { case conn := <-connections: cMap[conn.RemoteAddr().String()] = conn case client := <-clients: if regexp.MustCompile("^have ").MatchString(client.msg) { fMap[string(client.msg[5:len(client.msg)])] = client.local } if regexp.MustCompile("^list").MatchString(client.msg) { for key, value := range fMap { cMap[client.forserver].Write(strings.Bytes(key + "->" + value)) } cMap[client.forserver].Write(strings.Bytes("\n")) } } } }
func TestList(t *testing.T) { //var err os.Error vals := []string{"a", "b", "c", "d", "e"} for _, v := range vals { client.Rpush("l", strings.Bytes(v)) } if l, err := client.Llen("l"); err != nil || l != 5 { t.Fatal("Llen failed", err.String()) } for i := 0; i < len(vals); i++ { if val, err := client.Lindex("l", i); err != nil || string(val) != vals[i] { t.Fatal("Lindex failed", err.String()) } } for i := 0; i < len(vals); i++ { if err := client.Lset("l", i, strings.Bytes("a")); err != nil { t.Fatal("Lset failed", err.String()) } } for i := 0; i < len(vals); i++ { if val, err := client.Lindex("l", i); err != nil || string(val) != "a" { t.Fatal("Lindex failed", err.String()) } } client.Del("l") }
// Redis RENAME command. func (c *syncClient) Rename(arg0 string, arg1 string) (err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(arg1) _, err = c.conn.ServiceRequest(&RENAME, [][]byte{arg0bytes, arg1bytes}) return }
// Tests that gzipping and then gunzipping is the identity function. func TestWriter(t *testing.T) { pipe(t, func(deflater *Deflater) { deflater.Comment = "comment" deflater.Extra = strings.Bytes("extra") deflater.Mtime = 1e8 deflater.Name = "name" _, err := deflater.Write(strings.Bytes("payload")) if err != nil { t.Fatalf("%v", err) } }, func(inflater *Inflater) { b, err := ioutil.ReadAll(inflater) if err != nil { t.Fatalf("%v", err) } if string(b) != "payload" { t.Fatalf("payload is %q, want %q", string(b), "payload") } if inflater.Comment != "comment" { t.Fatalf("comment is %q, want %q", inflater.Comment, "comment") } if string(inflater.Extra) != "extra" { t.Fatalf("extra is %q, want %q", inflater.Extra, "extra") } if inflater.Mtime != 1e8 { t.Fatalf("mtime is %d, want %d", inflater.Mtime, uint32(1e8)) } if inflater.Name != "name" { t.Fatalf("name is %q, want %q", inflater.Name, "name") } }) }
func TestSet(t *testing.T) { var err os.Error vals := []string{"a", "b", "c", "d", "e"} for _, v := range vals { client.Sadd("s", strings.Bytes(v)) } var members [][]byte if members, err = client.Smembers("s"); err != nil || len(members) != 5 { t.Fatal("Set setup failed", err.String()) } for _, v := range vals { if ok, err := client.Sismember("s", strings.Bytes(v)); err != nil || !ok { t.Fatal("Sismember test failed") } } for _, v := range vals { if ok, err := client.Srem("s", strings.Bytes(v)); err != nil || !ok { t.Fatal("Sismember test failed") } } if members, err = client.Smembers("s"); err != nil || len(members) != 0 { t.Fatal("Set setup failed", err.String()) } client.Del("s") }
func TestPartialRead(t *testing.T) { f, err := os.Open("testdata/gnu.tar", os.O_RDONLY, 0444) if err != nil { t.Fatalf("Unexpected error: %v", err) } defer f.Close() tr := NewReader(f) // Read the first four bytes; Next() should skip the last byte. hdr, err := tr.Next() if err != nil || hdr == nil { t.Fatalf("Didn't get first file: %v", err) } buf := make([]byte, 4) if _, err := io.ReadFull(tr, buf); err != nil { t.Fatalf("Unexpected error: %v", err) } if expected := strings.Bytes("Kilt"); !bytes.Equal(buf, expected) { t.Errorf("Contents = %v, want %v", buf, expected) } // Second file hdr, err = tr.Next() if err != nil || hdr == nil { t.Fatalf("Didn't get second file: %v", err) } buf = make([]byte, 6) if _, err := io.ReadFull(tr, buf); err != nil { t.Fatalf("Unexpected error: %v", err) } if expected := strings.Bytes("Google"); !bytes.Equal(buf, expected) { t.Errorf("Contents = %v, want %v", buf, expected) } }
func TestGetByte(t *testing.T) { if b, _ := _GetByte(strings.Bytes("\x00\x11"), 1); b != 0x11 { t.Errorf("#1 Failed 0x%X != 0x11", b) } if _, e := _GetByte(strings.Bytes("\x00\x11"), 2); e == nil { t.Errorf("#2 Failed") } }
// Redis LTRIM command. func (c *syncClient) Ltrim(arg0 string, arg1 int64, arg2 int64) (err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(fmt.Sprintf("%d", arg1)) arg2bytes := strings.Bytes(fmt.Sprintf("%d", arg2)) _, err = c.conn.ServiceRequest(<RIM, [][]byte{arg0bytes, arg1bytes, arg2bytes}) return }
// Redis LSET command. func (c *syncClient) Lset(arg0 string, arg1 int64, arg2 []byte) (err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(fmt.Sprintf("%d", arg1)) arg2bytes := arg2 _, err = c.conn.ServiceRequest(&LSET, [][]byte{arg0bytes, arg1bytes, arg2bytes}) return }
// compare two clients: name and network connection func (c *ClientChat) Equal(cl *ClientChat) bool { if bytes.Equal(strings.Bytes(c.Name), strings.Bytes(cl.Name)) { if c.Con == cl.Con { return true } } return false }
func SaveKeys(n, e, d, p, q *big.Int) { pu := strings.Bytes(n.String() + "\n" + e.String() + "\n") pr := strings.Bytes(p.String() + "\n" + q.String() + "\n" + d.String() + "\n") if ioutil.WriteFile(*publicKeyFile, pu, 0600) != nil || ioutil.WriteFile(*privateKeyFile, pr, 0600) != nil { panic("Writing problems") } }
func checkAppendString(t *testing.T, input []string, expected string) { buff := bytes.NewBuffer([]byte{}) for _, str := range input { _AppendString(buff, str) } if !bytes.Equal(strings.Bytes(expected), buff.Bytes()) { t.Error("Failed:expected", strings.Bytes(expected), ", actual:", buff.Bytes()) } }
func Digest(key string, m string) string { myhash := hmac.NewSHA1(strings.Bytes(key)); myhash.Write(strings.Bytes(m)); signature := bytes.TrimSpace(myhash.Sum()); digest := make([]byte, base64.StdEncoding.EncodedLen(len(signature))); base64.StdEncoding.Encode(digest, signature); digest_str := strings.TrimSpace(bytes.NewBuffer(digest).String()); return digest_str; }
func TestIndex(t *testing.T) { for _, tt := range indextests { a := strings.Bytes(tt.a) b := strings.Bytes(tt.b) pos := Index(a, b) if pos != tt.i { t.Errorf(`Index(%q, %q) = %v`, tt.a, tt.b, pos) } } }
func TestGetString(t *testing.T) { s, e := _GetString(strings.Bytes("\x00\x00test"), 2, 4) if e != nil || s != "test" { t.Error("#1 Failed") } s, e = _GetString(strings.Bytes("1234"), 3, 1) if e != nil || s != "4" { t.Error("#2 Failed") } }
// Redis RENAME command. func (c *async) Rename(arg0 string, arg1 string) (stat FutureBool, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(arg1) resp, err := c.conn.QueueRequest(&RENAME, [][]byte{arg0bytes, arg1bytes}) if err == nil { stat = resp.future.(FutureBool) } return }
func TestRepeat(t *testing.T) { for _, tt := range RepeatTests { tin := strings.Bytes(tt.in) tout := strings.Bytes(tt.out) a := Repeat(tin, tt.count) if !Equal(a, tout) { t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout) continue } } }
// WriteHeader writes hdr and prepares to accept the file's contents. // WriteHeader calls Flush if it is not the first header. // Calling after a Close will return ErrWriteAfterClose. func (tw *Writer) WriteHeader(hdr *Header) os.Error { if tw.closed { return ErrWriteAfterClose } if tw.err == nil { tw.Flush() } if tw.err != nil { return tw.err } tw.nb = int64(hdr.Size) tw.pad = -tw.nb & (blockSize - 1) // blockSize is a power of two header := make([]byte, blockSize) s := slicer(header) // TODO(dsymonds): handle names longer than 100 chars copy(s.next(100), strings.Bytes(hdr.Name)) tw.octal(s.next(8), hdr.Mode) // 100:108 tw.numeric(s.next(8), hdr.Uid) // 108:116 tw.numeric(s.next(8), hdr.Gid) // 116:124 tw.numeric(s.next(12), hdr.Size) // 124:136 tw.numeric(s.next(12), hdr.Mtime) // 136:148 s.next(8) // chksum (148:156) s.next(1)[0] = hdr.Typeflag // 156:157 s.next(100) // linkname (157:257) copy(s.next(8), strings.Bytes("ustar\x0000")) // 257:265 tw.cString(s.next(32), hdr.Uname) // 265:297 tw.cString(s.next(32), hdr.Gname) // 297:329 tw.numeric(s.next(8), hdr.Devmajor) // 329:337 tw.numeric(s.next(8), hdr.Devminor) // 337:345 // Use the GNU magic instead of POSIX magic if we used any GNU extensions. if tw.usedBinary { copy(header[257:265], strings.Bytes("ustar \x00")) } // The chksum field is terminated by a NUL and a space. // This is different from the other octal fields. chksum, _ := checksum(header) tw.octal(header[148:155], chksum) header[155] = ' ' if tw.err != nil { // problem with header; probably integer too big for a field. return tw.err } _, tw.err = tw.w.Write(header) return tw.err }
func TestAppendByte(t *testing.T) { buff := bytes.NewBuffer([]byte{}) _AppendByte(buff, 1) if !bytes.Equal(strings.Bytes("\x01"), buff.Bytes()) { t.Error("#1 Failed") } _AppendByte(buff, 2) if !bytes.Equal(strings.Bytes("\x01\x02"), buff.Bytes()) { t.Error("#2 Failed") } }
func main() { // Dial freenode log.Stdout("Dialing server") server, err := IRCDial("tcp", "", "irc.freenode.net:6667") // TODO: make this not hardcoded if err != nil { log.Exit("Dialing error:", err) } // Login to the server log.Stdout("Logging in to server") server.Login("goo_bot", FlagInvisible) // Send a PM to NickServ to identify log.Stdout("Identifying to Nickserv") server.PrivMsg("NickServ", "identify go_bot turing") // Join a chat log.Stdout("Joining #bottest") bottest, _ := server.Join("#bottest") // TODO: log the errors // Send the chat a message log.Stdout("Greeting #bottest") bottest.Write("hi guys!") // We're done with the connection, close it log.Stdout("Sleeping before closing") time.Sleep(1e10) log.Stdout("Closing") server.Close() // Talk to server (loop forever) connReader := bufio.NewReader(server.Conn) for i := 0; i < 100; i++ { response, err := connReader.ReadString('\n') if err != nil { log.Exit("Error reading from connection:", err) } log.Stdoutf("RECEIVED: %s", strings.TrimSpace(response)) if response[0] != ':' { //not a private message wd := strings.Split(response, " ", 2) log.Stdout("Got Message ", wd[0]) switch wd[0] { // Message Type case "PING": // TODO: find a better way to remove leading character in string pongServer := string(strings.Bytes(wd[1])[1:len(wd[1])]) pong := "PONG " + pongServer + "\r\n" log.Stdout("SENT: ", pong) server.Conn.Write(strings.Bytes(pong)) } } } // We're done with the connection, close it log.Stdout("Sleeping before closing") time.Sleep(1e10) log.Stdout("Closing") server.Close() }
func TestAppendUint32(t *testing.T) { buff := bytes.NewBuffer([]byte{}) _AppendUint32(buff, 1) if !bytes.Equal(strings.Bytes("\x01\x00\x00\x00"), buff.Bytes()) { t.Error("#1 Failed") } _AppendByte(buff, 2) _AppendUint32(buff, 0xffffffff) if !bytes.Equal(strings.Bytes("\x01\x00\x00\x00\x02\x00\x00\x00\xff\xff\xff\xff"), buff.Bytes()) { t.Error("#2 Failed") } }
// Redis LSET command. func (c *asyncClient) Lset(arg0 string, arg1 int64, arg2 []byte) (stat FutureBool, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(fmt.Sprintf("%d", arg1)) arg2bytes := arg2 resp, err := c.conn.QueueRequest(&LSET, [][]byte{arg0bytes, arg1bytes, arg2bytes}) if err == nil { stat = resp.future.(FutureBool) } return }
// Redis MOVE command. func (c *syncClient) Move(arg0 string, arg1 int64) (result bool, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(fmt.Sprintf("%d", arg1)) var resp Response resp, err = c.conn.ServiceRequest(&MOVE, [][]byte{arg0bytes, arg1bytes}) if err == nil { result = resp.GetBooleanValue() } return result, err }
func urlquoter(c int, safe string) []byte { safe_bytes := strings.Bytes(safe); c_bytes := make([]byte, utf8.RuneLen(c)); utf8.EncodeRune(c, c_bytes); if bytes.Index(safe_bytes, c_bytes) != -1 || bytes.Index(always_safe, c_bytes) != -1 { return c_bytes; } else { return strings.Bytes(fmt.Sprintf("%%%02X", c)); } panic("unreachable"); }
// Redis LINDEX command. func (c *asyncClient) Lindex(arg0 string, arg1 int64) (result FutureBytes, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(fmt.Sprintf("%d", arg1)) var resp *PendingResponse resp, err = c.conn.QueueRequest(&LINDEX, [][]byte{arg0bytes, arg1bytes}) if err == nil { result = resp.future.(FutureBytes) } return result, err }
func TestCopy(t *testing.T) { for i := 0; i < len(copytests); i++ { tt := copytests[i] dst := strings.Bytes(tt.a) n := Copy(dst, strings.Bytes(tt.b)) result := string(dst) if result != tt.res || n != tt.n { t.Errorf(`Copy(%q, %q) = %d, %q; want %d, %q`, tt.a, tt.b, n, result, tt.n, tt.res) continue } } }
// Redis RENAMENX command. func (c *async) Renamenx(arg0 string, arg1 string) (result FutureBool, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(arg1) var resp *PendingResponse resp, err = c.conn.QueueRequest(&RENAMENX, [][]byte{arg0bytes, arg1bytes}) if err == nil { result = resp.future.(FutureBool) } return result, err }
// Redis MOVE command. func (c *async) Move(arg0 string, arg1 int64) (result FutureBool, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(fmt.Sprintf("%d", arg1)) var resp *PendingResponse resp, err = c.conn.QueueRequest(&MOVE, [][]byte{arg0bytes, arg1bytes}) if err == nil { result = resp.future.(FutureBool) } return result, err }
// Redis RPOPLPUSH command. func (c *async) Rpoplpush(arg0 string, arg1 string) (result FutureBytes, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(arg1) var resp *PendingResponse resp, err = c.conn.QueueRequest(&RPOPLPUSH, [][]byte{arg0bytes, arg1bytes}) if err == nil { result = resp.future.(FutureBytes) } return result, err }
// Redis LTRIM command. func (c *async) Ltrim(arg0 string, arg1 int64, arg2 int64) (stat FutureBool, err Error) { arg0bytes := strings.Bytes(arg0) arg1bytes := strings.Bytes(fmt.Sprintf("%d", arg1)) arg2bytes := strings.Bytes(fmt.Sprintf("%d", arg2)) resp, err := c.conn.QueueRequest(<RIM, [][]byte{arg0bytes, arg1bytes, arg2bytes}) if err == nil { stat = resp.future.(FutureBool) } return }