Exemplo n.º 1
0
func main() {
	var straddr string
	flag.StringVar(&straddr, "a", "", "Address of the exporter")
	flag.Parse()
	if straddr == "" {
		flag.Usage()
		log.Exit("No address given")
	}
	bstdin := bufio.NewReader(os.Stdin)
	var err os.Error
	done := make(chan os.Error)
	imp, err := netchan.NewImporter("tcp", straddr)
	if err != nil {
		log.Exit("Error creating importer: ", err)
	}
	go func() {
		for line, err := bstdin.ReadString('\n'); err == nil; line, err = bstdin.ReadString('\n') {
			go importChan(imp, strings.TrimSpace(line), done)
			go func() {
				err := <-done
				log.Println(err)
			}()
		}
		log.Exit("Error reading stdin: ", err)
	}()
	<-done
}
Exemplo n.º 2
0
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"))
			}
		}
	}
}
Exemplo n.º 3
0
func audioServer() {
	// Native Client requires that all audio calls
	// original from a single OS thread.
	runtime.LockOSThread()

	n, err := av.AudioStream(nil)
	if err != nil {
		log.Exit(err)
	}
	for {
		b := <-sndc
		for len(b)*2 >= n {
			var a []uint16
			a, b = b[0:n/2], b[n/2:]
			n, err = av.AudioStream(a)
			if err != nil {
				log.Exit(err)
			}
			println(n, len(b)*2)
		}
		a := make([]uint16, n/2)
		for i := range b {
			a[i] = b[i]
		}
		n, err = av.AudioStream(a)
	}
}
Exemplo n.º 4
0
func newIRC(c net.Conn) (irc *IRC) {
	irc = &IRC{Reader: make(chan string, 10), Writer: make(chan string, 10)}

	// start reader
	go func(r *bufio.Reader) {
		for {
			line, err := r.ReadString('\n')
			if err != nil {
				log.Exit("Unable to read from channel", err)
			}
			log.Stdoutf("Read: %#v", line)
			irc.Reader <- line
		}
	}(bufio.NewReader(c))

	// start writer
	go func(w *bufio.Writer) {
		for {
			line := <-irc.Writer
			_, err := w.WriteString(line)
			if err != nil {
				log.Exit("Unable to write to channel", err)
			}
			err = w.Flush()
			if err != nil {
				log.Exit("Unable to write to channel", err)
			}
			log.Stdoutf("Wrote: %#v", line)
		}
	}(bufio.NewWriter(c))

	return irc
}
Exemplo n.º 5
0
func main() {
	// Read the string
	inputReader := bufio.NewReader(os.Stdin)

	var info = Metadata{"", uint32(0), nil}
	var cmd = Command{"", nil, nil, nil, ""}

	infoJson, err := inputReader.ReadString('\n')
	if err != nil {
		log.Exit(err)
	} else {
		json.Unmarshal(infoJson, &info)
	}

	bpt, bperr := bptree.NewBpTree(info.Filename, info.Keysize, info.Fieldsizes)
	if !bperr {
		log.Exit("Failed B+ tree creation")
	} else {
		fmt.Println("ok")
	}

	alive := true

	for alive {
		cmdJson, err := inputReader.ReadString('\n')
		if err != nil {
			alive = false
			break
		}
		if cmdJson == "q\n" {
			alive = false
		} else {
			json.Unmarshal(cmdJson, &cmd)
			if cmd.Op == "insert" {
				result := bpt.Insert(cmd.LeftKey, cmd.Fields)
				fmt.Println(result)
			} else if cmd.Op == "find" {
				records, ack := bpt.Find(cmd.LeftKey, cmd.RightKey)
				for record := range records {
					json.Marshal(os.Stdout, map[string]interface{}{
						"key":   record.GetKey(),
						"value": record.AllFields()})
					fmt.Println()
					ack <- true
				}
				fmt.Println("end")
			} else if cmd.Op == "visualize" {
				bptree.Dotty(cmd.FileName, bpt)
			} else if cmd.Op == "prettyprint" {
				s := fmt.Sprintln(bpt)
				f, _ := os.Open(cmd.FileName, os.O_RDWR|os.O_CREAT, 0666)
				f.Write([]byte(s))
				f.Close()
			}
		}
	}
	fmt.Println("exited")
}
Exemplo n.º 6
0
// Allocates a new key block. This isn't quite as convient as the method
// for BTrees as we have to tell it if we are allocating an internal or an
// external block.
func (self *BpTree) allocate(dim *BlockDimensions) *KeyBlock {
	if dim != self.external && dim != self.internal {
		log.Exit("Cannot allocate a block that has dimensions that are niether the dimensions of internal or external nodes.")
	}
	block, ok := NewKeyBlock(self.bf, dim)
	if !ok {
		log.Exit("Could not allocate block PANIC")
	}
	return block
}
Exemplo n.º 7
0
func main() {
	if len(os.Args) != 2 {
		log.Exit("Usage: " + os.Args[0] + " n")
	}
	i, err := strconv.Atoi(os.Args[1])
	if err != nil {
		log.Exit(err)
	}
	res := fib(i)
	println(res)
}
Exemplo n.º 8
0
func InitTables(dbh *sqlite3.Handle) {
	st, err := dbh.Prepare("CREATE TABLE IF NOT EXISTS entry (id INTEGER PRIMARY KEY, body VARCHAR(255));")
	if err != "" {
		log.Exit(err)
	}
	if st.Step() != sqlite3.SQLITE_DONE {
		log.Exit(dbh.ErrMsg())
	}
	if st.Finalize() != sqlite3.SQLITE_OK {
		log.Exit(dbh.ErrMsg())
	}
}
Exemplo n.º 9
0
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()
}
Exemplo n.º 10
0
func main() {
	t := template.New(nil)
	t.SetDelims("«", "»")
	err := t.Parse(templateStr)
	if err != nil {
		log.Exit(err)
	}
	err = t.Execute(data, os.Stdout)
	if err != nil {
		log.Exit(err)
	}
}
Exemplo n.º 11
0
func main() {
	client, err := rpc.DialHTTP("tcp", "localhost:1234")
	if err != nil {
		log.Exit("dialing:", err)
	}
	args := &arith.Args{7, 8}
	reply := new(arith.Reply)
	err = client.Call("Arith.Add", args, reply)
	if err != nil {
		log.Exit("arith error:", err)
	}
	fmt.Printf("Arith: %d+%d=%d\n", args.A, args.B, reply.C)
}
Exemplo n.º 12
0
func main() {
	r, err := jsonrpc.Dial("tcp", "localhost:6666")
	if err != nil {
		log.Exit("Error dialing host: ", err)
	}
	remote := &TestRPCSrv{r}
	a := "foo"
	var b string
	err = remote.Call("testApp.PrintStuff", &a, &b)
	if err != nil {
		log.Exit("Error calling function: ", err)
	}
	log.Exit(b)
}
Exemplo n.º 13
0
func client(host string, port int) {
	client, err := rpc.DialHTTP("tcp", host+":"+fmt.Sprintf("%d", port))
	if err != nil {
		log.Exit("dialing:", err)
	}

	var reply string
	err = client.Call("ProcessStarter.Start", processMap["server"], &reply)
	if err != nil {
		log.Exit("error:", err)
	}
	//    fmt.Printf("Arith: %d*%d=%d", args.A, args.B, *reply)

}
Exemplo n.º 14
0
func main() {
	// This works
	r, _, err := http.Get("https://www.google.com")
	if err != nil {
		log.Exit(err)
	}
	log.Println(r)

	// This doesn't
	r, _, err = http.Get("https://streaming.campfirenow.com")
	if err != nil {
		log.Exit(err)
	}
	log.Println(r)
}
Exemplo n.º 15
0
Arquivo: main.go Projeto: ox/GoStones
func git_from_net(url string) string {
	var args [3]string
	args[0] = "git"
	args[1] = "clone"
	args[2] = url
	var fds []*os.File = new([3]*os.File)
	fds[0] = os.Stdin
	fds[1] = os.Stdout
	fds[2] = os.Stderr

	_, str := path.Split(url)
	name := strings.Split(str, ".", -1)[0]
	var git_path string

	switch os.Getenv("GOOS") {
	case "darwin":
		git_path = "/usr/local/git/bin/git"
		break
	case "linux":
		git_path = "/opt/local/bin/git"
		break
	}

	/* Replace this with git's full path, or use a shell, and then call git in the args */
	pid, err := os.ForkExec(git_path, &args, os.Envs, os.Getenv("GOROOT")+"/src/pkg/", fds)
	if err != nil {
		log.Exit(err)
	}

	os.Wait(pid, 0)

	return string(os.Getenv("GOROOT") + "/src/pkg/" + name)
}
Exemplo n.º 16
0
func main() {
	// start a connection with the server
	irc, err := DialIRC("", "irc.freenode.net:6667")
	if err != nil {
		log.Exit("Error connecting:", err)
	}
	irc.Log("Hello, world!")

	// Login w/ a default name and user
	irc.Login("go_bot")
	// Join a chat. Yay LUG!
	irc.Join("#bottest")

	// Get messages, handle them
	for { // loop forever
		line := <-irc.Rec
		words := strings.Split(line, " ", 3)
		irc.Log(ParseUser(words[0]))
		switch words[1] { // Message Type
		case "PRIVMSG":
			go irc.Hi(words[2])
			continue
		}

	}

	time.Sleep(6e10) // Wait a minute
	irc.Log("Closing")
	irc.Close()
}
Exemplo n.º 17
0
func main() {
	http.HandleFunc("/", ProxyServer)
	err := http.ListenAndServe(":8123", nil)
	if err != nil {
		log.Exit("ListenAndServe: ", err.String())
	}
}
Exemplo n.º 18
0
func main() {
	// Dial freenode
	log.Stdout("Dialing server")
	server, err := irc.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", irc.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()
}
Exemplo n.º 19
0
func main() {
	flag.Parse()
	go hub()
	http.Handle("/broadcast", websocket.Handler(clientHandler))
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemplo n.º 20
0
func processEvent(ch <-chan interface{}) {
	for {
		if closed(ch) {
			log.Exit("X display closed.")
		}
		ev, ok := <-ch
		if !ok {
			// no events, return
			return
		}

		switch ev.(type) {
		case draw.ErrEvent:
			log.Exit("X11 err: ", ev.(draw.ErrEvent).Err)
		}
	}
}
Exemplo n.º 21
0
func main() {
	flag.Parse()
	http.Handle("/", http.HandlerFunc(QR))
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemplo n.º 22
0
func getstdin() string {
	bytes := make([]byte, 1000)
	n, err := os.Stdin.Read(bytes)
	if err != nil {
		log.Exit("Could not read from stdin", err)
	}
	return string(bytes[0:n])
}
Exemplo n.º 23
0
func main() {
	calc, err := NewCalcServiceClient("MyCalcService", "tcp", "", "127.0.0.1:1234")
	if err != nil {
		log.Exit("cant setup calc service:", err)
	}

	doCalc(calc)
}
Exemplo n.º 24
0
//runs the web application and serves http requests
func Run(addr string) {
	http.Handle("/", http.HandlerFunc(httpHandler))

	log.Stdoutf("web.go serving %s", addr)
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemplo n.º 25
0
// Accept accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func (server *Server) Accept(lis net.Listener) {
	for {
		conn, err := lis.Accept()
		if err != nil {
			log.Exit("rpc.Serve: accept:", err.String()) // TODO(r): exit?
		}
		go server.ServeConn(conn)
	}
}
Exemplo n.º 26
0
Arquivo: web.go Projeto: ality/web.go
func (s *Server) Run(addr string) {
	mux := http.NewServeMux()
	mux.Handle("/", s)
	s.Logger.Printf("web.go serving %s\n", addr)
	err := http.ListenAndServe(addr, mux)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemplo n.º 27
0
func server() {
	ps := new(ProcessStarter)
	rpc.Register(ps)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Exit("listen error:", e)
	}
	go http.Serve(l, nil)
}
Exemplo n.º 28
0
func RunServer(addr string) {
	self := new(Server).Init()
	rpc.Register(self)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", addr)
	if e != nil {
		log.Exit("listen error: ", e)
	}
	http.Serve(l, nil)
}
Exemplo n.º 29
0
func main() {
	arith := new(arith.Arith)
	rpc.Register(arith)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Exit("listen error: ", e)
	}
	http.Serve(l, nil)
}
Exemplo n.º 30
0
func loadStartPosition(worldPath string) {
	file, err := os.Open(path.Join(worldPath, "level.dat"), os.O_RDONLY, 0)
	if err != nil {
		log.Exit("loadStartPosition: ", err.String())
	}

	level, err := nbt.Read(file)
	file.Close()
	if err != nil {
		log.Exit("loadStartPosition: ", err.String())
	}

	pos := level.Lookup("/Data/Player/Pos")
	StartPosition = XYZ{
		pos.(*nbt.List).Value[0].(*nbt.Double).Value,
		pos.(*nbt.List).Value[1].(*nbt.Double).Value,
		pos.(*nbt.List).Value[2].(*nbt.Double).Value,
	}
}