Exemple #1
0
func main() {
	var host *string = flag.String("host", "localhost", "hostname")
	var port *int = flag.Int("port", 9999, "port")
	flag.Parse()

	var ipAddr string = *host + ":" + strconv.Itoa(*port)
	log.Stdoutf("host=[%s] port=%d addr=[%s]", *host, *port, ipAddr)

	udpAddr, err := net.ResolveUDPAddr(ipAddr)
	if udpAddr == nil {
		log.Stdoutf("ResolveUDPAddr failed: %s", err.String())
		os.Exit(1)
	}
	udpConn, err := net.ListenUDP("udp", udpAddr)
	if udpConn == nil {
		log.Stdoutf("ListenUDP failed: %s", err.String())
		os.Exit(1)
	}
	udpConn.SetReadTimeout(10)
	stscall.SetNonblock(udpConn.fd, false)
	var buff [50]byte
	sz, rUdpAddr, err := udpConn.ReadFromUDP(&buff)
	if err != nil {
		log.Stdoutf("Read failed: %s", err.String())
		os.Exit(1)
	}
	log.Stdoutf("read from remote addr: [%s] sz=%d buff=[%s]", rUdpAddr.String(), sz, buff)
	//    var udpAddr *net.UDPAddr, err os.Error = net.ResolveUDPAddr(ipAddr);
}
func handleMessage(s net.Conn, reqChannel chan MCRequest) (ret bool) {
	log.Stdoutf("Handling a message...")
	hdrBytes := make([]byte, HDR_LEN)
	ret = false

	log.Stdoutf("Reading header...")
	bytesRead, err := io.ReadFull(s, hdrBytes)
	if err != nil || bytesRead != HDR_LEN {
		log.Stderr("Error reading message: %s (%d bytes)", err, bytesRead)
		return
	}

	req := grokHeader(hdrBytes)

	readContents(s, req)

	log.Stdout("Processing message %s", req)
	req.ResponseChannel = make(chan MCResponse)
	reqChannel <- req
	res := <-req.ResponseChannel
	ret = !res.Fatal
	if ret {
		log.Stdoutf("Got response %s", res)
		transmitResponse(s, req, res)
	} else {
		log.Stderr("Something went wrong, hanging up...")
	}

	return
}
Exemple #3
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
}
Exemple #4
0
func (l *writeLogger) Write(p []byte) (n int, err os.Error) {
	n, err = l.w.Write(p)
	if err != nil {
		log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err)
	} else {
		log.Stdoutf("%s %x", l.prefix, p[0:n])
	}
	return
}
Exemple #5
0
func (l *readLogger) Read(p []byte) (n int, err os.Error) {
	n, err = l.r.Read(p)
	if err != nil {
		log.Stdoutf("%s %x: %v", l.prefix, p[0:n], err)
	} else {
		log.Stdoutf("%s %x", l.prefix, p[0:n])
	}
	return
}
/**
 * GetUserTimeline gets the user's timeline (provided by screenName) using the credentials
 * saved in the Client provided.
 */
func GetUserTimeline(client *Client, screenName string) (statuses []Status, err os.Error) {
	log.Stdout("Get User's Timeline\n")
	// get json response from server
	var jsonStrResponse string
	var maxFetchCount = client.MaxFetchCount
	if maxFetchCount == 0 {
		maxFetchCount = DefaultMaxFetchCount
	} // use a default

	// send request
	jsonStrResponse, err = send(URLUserTimeline+"?screen_name="+screenName+"&count="+strconv.Itoa(maxFetchCount), "GET", nil, client, "")
	if err != nil {
		return nil, err
	}

	// parse json response
	var resultObj json.Json
	//log.Stdout("response: %s", jsonStrResponse);
	resultObj, err = parseJson(jsonStrResponse)
	if err != nil {
		return nil, err
	}

	// create status response
	var i int
	statuses = make([]Status, resultObj.Len())
	log.Stdoutf("result count: %d", resultObj.Len())
	for i = 0; i < len(statuses); i++ {
		var elem = resultObj.Elem(i)
		//log.Stdoutf("found status: %s\n", elem.Get("text").String());
		statuses[i] = *parseStatus(elem)
	}
	return
}
/**
 * GetDirectMessages gets all of your direct messages. It uses the credentials
 * saved in the Client provided.
 */
func GetDirectMessages(client *Client) (statuses []Status, err os.Error) {
	log.Stdout("Get Direct Messages\n")
	// get json response from server
	var jsonStrResponse string
	var maxFetchCount = client.MaxFetchCount
	if maxFetchCount == 0 {
		maxFetchCount = DefaultMaxFetchCount
	} // use a default

	// send request
	jsonStrResponse, err = send(URLDirectMessages+"?count="+strconv.Itoa(maxFetchCount), "GET", nil, client, "")
	if err != nil {
		return nil, err
	}

	// parse json response
	var resultObj json.Json
	//log.Stdout("response: %s", jsonStrResponse);
	resultObj, err = parseJson(jsonStrResponse)
	if err != nil {
		return nil, err
	}

	// create status response
	var i int
	statuses = make([]Status, resultObj.Len())
	log.Stdoutf("result count: %d", resultObj.Len())
	for i = 0; i < len(statuses); i++ {
		statuses[i] = *parseDirectMessage(resultObj.Elem(i))
	}
	return
}
/**
 * GetMentions gets all mentions of you using the credentials
 * saved in the Client provided.
 */
func GetMentions(client *Client) (statuses []Status, err os.Error) {
	log.Stdout("Get Mentions\n")
	// get json response from server
	var jsonStrResponse string
	var maxFetchCount = client.MaxFetchCount
	if maxFetchCount == 0 {
		maxFetchCount = DefaultMaxFetchCount
	} // use a default
	var form = map[string][]string{
		"count": []string{strconv.Itoa(maxFetchCount)},
	}

	// send request
	jsonStrResponse, err = send(URLMentions, "GET", form, client, "count="+strconv.Itoa(maxFetchCount))
	if err != nil {
		return nil, err
	}

	// parse json response
	var resultObj json.Json
	resultObj, err = parseJson(jsonStrResponse)
	if err != nil {
		return nil, err
	}

	// create status response
	var i int
	statuses = make([]Status, resultObj.Len())
	log.Stdoutf("result count: %d", resultObj.Len())
	for i = 0; i < len(statuses); i++ {
		var elem = resultObj.Elem(i)
		statuses[i] = *parseStatus(elem)
	}
	return
}
Exemple #9
0
func NewConsoleLogger(logLevel Severity) *ConsoleLogger {
	logger := &ConsoleLogger{}
	logger.base = &base{}
	logger.base.LogLevel = logLevel
	logger.base.addFunc = func(severity Severity, format string, v ...interface{}) { log.Stdoutf(format, v) }
	return logger
}
Exemple #10
0
func main() {
	var address, key string
	var count, delay, step int
	flag.StringVar(&address, "address", "127.0.0.1:6311", "Set the port (+optional address) to send packets to")
	flag.StringVar(&key, "key", "profile", "Set the key name (pakets data will be \"key:idx\")")
	flag.IntVar(&count, "count", 1000, "Set the number of packets to send")
	flag.IntVar(&delay, "delay", 1000000, "Set the delay between packets in nanoseconds (10^-9)")
	flag.IntVar(&step, "step", 100, "Log step (how many packets to send between logging)")
	flag.Parse()

	udp_address, error := net.ResolveUDPAddr(address)
	if error != nil {
		log.Exitf("Cannot parse \"%s\": %s", address, error)
	}

	log.Stdout(udp_address)

	ticker := time.NewTicker(int64(delay))
	defer ticker.Stop()

	for sent := 1; sent <= count; sent++ {
		<-ticker.C
		send(udp_address, key, sent)
		if sent%step == 0 {
			log.Stdoutf("Processed %d packets of %d", sent, count)
		}
	}
}
Exemple #11
0
// handle a request to change the status
func HandleUpdateStatus(c *http.Conn, req *http.Request) {
	req.ParseForm()
	statusStr := req.FormValue("status")
	log.Stdoutf("status to be sent:\n%s\n\n", statusStr)
	jsonStr, _ := twitter.TweetJson(&creds, statusStr)
	io.WriteString(c, jsonStr)
}
Exemple #12
0
func (bot *Bot) Process(message *Message, out chan string) {
	switch message.Command {
	case "PING":
		message.Ping(out)
	default:
		log.Stdoutf("%#v", message)
	}
}
Exemple #13
0
func (s *Server) Run(addr string) {
	mux := http.NewServeMux()
	mux.Handle("/", s)
	log.Stdoutf("web.go serving %s", addr)
	err := http.ListenAndServe(addr, mux)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemple #14
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)
	}
}
Exemple #15
0
func (this *action) Call(method string, data interface{}) interface{} {
	switch method {
	case "hello":
		return "Hello world"
	case "echo":
		v, ok := data.([]interface{})
		if !ok {
			log.Stdoutf("first echo type assertion not ok")
			return nil
		}
		v2, ok2 := v[0].(map[string]interface{})
		if !ok2 {
			log.Stdoutf("second echo type assertion not ok")
			return nil
		}
		return v2["message"]
	}
	return nil
}
Exemple #16
0
func (bot *Bot) Accept(line string, out chan string) {
	command := R.FindStringSubmatch(line)
	if command != nil {
		log.Stdoutf("%#v", command)
		bot.Process(&Message{
			Prefix:  command[2],
			Command: command[3],
			Params:  P.FindStringSubmatch(command[5]),
		}, out)
	}
}
Exemple #17
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()
}
Exemple #18
0
func (this *Action) Render(context interface{}) string {
	log.Stdoutf("Rendering %s", this.template)
	filename := GetConfig("templates") + "/" + this.template + ".mustache"
	output, err := mustache.RenderFile(filename, context)
	if err != nil {
		log.Stderrf("Error on rendering %s", filename, err)
		return "" // TODO error page
	}
	if this.layout != nil {
		output = this.layout.Render(map[string]string{"yield": output})
	}
	return output
}
Exemple #19
0
func (this *formAction) Call(method string, data interface{}) interface{} {
	switch method {
	case "load":
		d := map[string]string{"myfield": "flam floo"}
		return map[string]interface{}{
			"success": true,
			"data":    d,
		}
	case "submit":
		v, ok := data.([]interface{})
		if !ok {
			log.Stdoutf("first submit type assertion not ok")
			return false
		}
		v2, ok2 := v[0].(map[string][]string)
		if !ok2 {
			log.Stdoutf("second submit type assertion not ok")
			return false
		}
		return v2["myfield"][0] == "flam floo"
	}
	return nil
}
Exemple #20
0
// AudioStream provides access to the audio device.
// Each call to AudioStream writes the given data,
// which should be a slice of 16-bit stereo PCM audio samples,
// and returns the number of samples required by the next
// call to AudioStream.
//
// To find out the initial number of samples to write, call AudioStream(nil).
//
func AudioStream(data []uint16) (nextSize int, err os.Error) {
	if audioSize == 0 {
		e := os.NewSyscallError("audio_stream", syscall.AudioStream(nil, &audioSize))
		return int(audioSize), e
	}
	if data == nil {
		return int(audioSize), nil
	}
	if uintptr(len(data))*2 != audioSize {
		log.Stdoutf("invalid audio size want %d got %d", audioSize, len(data))
	}
	e := os.NewSyscallError("audio_stream", syscall.AudioStream(&data[0], &audioSize))
	return int(audioSize), e
}
Exemple #21
0
func waitForConnections(ls net.Listener) {
	reqChannel := make(chan MCRequest)
	go mc_storage.RunServer(reqChannel)
	log.Stdoutf("Listening on port %d", *port)
	for {
		s, e := ls.Accept()
		if e == nil {
			log.Stdout("Got a connection %s", s)
			go mc_conn_handler.HandleIO(s, reqChannel)
		} else {
			log.Stderr("Error accepting from %s", ls)
		}
	}
}
/**
 * DoSearch searches all status updates for a particular pattern.
 */
func DoSearch(client *Client, query string) (searchResults []SearchResult, err os.Error) {
	log.Stdout("Do Search\n")
	// get json response from server
	var jsonStrResponse string
	var maxFetchCount = client.MaxFetchCount
	if maxFetchCount == 0 {
		maxFetchCount = DefaultMaxFetchCount
	} // use a default
	query = http.URLEscape(query) // make query safe to travel in http body/url
	var maxFetchCountStr = strconv.Itoa(maxFetchCount)

	// send request
	log.Stdoutf("max fetch count: %s\n", maxFetchCountStr)
	var url = URLSearch + "?q=" + query + "&rpp=" + maxFetchCountStr
	jsonStrResponse, err = send(url, "GET", nil, client, "")
	if err != nil {
		return nil, err
	}

	// parse json response
	var resultObj json.Json
	resultObj, err = parseJson(jsonStrResponse)
	if err != nil {
		return nil, err
	}

	// create status response
	var i int
	resultObj = resultObj.Get("results")
	searchResults = make([]SearchResult, resultObj.Len())
	log.Stdoutf("result count: %d", resultObj.Len())
	for i = 0; i < len(searchResults); i++ {
		var elem = resultObj.Elem(i)
		searchResults[i] = *parseSearchResults(elem)
	}
	return
}
Exemple #23
0
func (this *router) decodeTransaction(r io.Reader) []*Request {
	jsonData, _ := ioutil.ReadAll(r)
	var reqs []*Request
	err := json.Unmarshal(jsonData, &reqs)
	if err != nil {
		// attempt to unmarshal as single request
		var req *Request
		err = json.Unmarshal(jsonData, &req)
		if err != nil {
			log.Stdoutf("err %v", err)
			return nil
		}
		reqs = []*Request{req}
	}
	return reqs
}
Exemple #24
0
func main() {
	runtime.GOMAXPROCS(4)

	log.Stdout("Starting basic HTTP server...\n")

	tcp_listen_addr := &net.TCPAddr{net.IPv4(0, 0, 0, 0), 0}
	listener, listenErr := net.ListenTCP("tcp", tcp_listen_addr)

	if listenErr != nil {
		log.Stderr(listenErr.String())
	}
	log.Stdoutf("Listening on port: %s\n", listener.Addr().String())

	http.HandleFunc("/hello", handler)
	http.Serve(listener, nil)
	listener.Close()
	log.Stdout("Done.")
}
Exemple #25
0
func main() {
	// Determine execuable dir
	execpath, err := exec.LookPath(os.Args[0])
	if err != nil {
		log.Exitf("Unable to determine executable path")
	}
	// Absolutise execpath: Seems the best way in absence of Realpath
	if pwd, err := os.Getwd(); err == nil {
		execpath = pathutil.Clean(pathutil.Join(pwd, execpath))
	} else {
		log.Exitf("Getwd: %s", err)
	}
	execdir, _ := pathutil.Split(execpath)

	tmplroot = flag.String("root", pathutil.Join(execdir, "templates"), "root directory for templates")
	flag.Parse()
	log.Stdoutf("Using template dir: %s", *tmplroot)
	readTemplates()

	http.Handle("/", http.HandlerFunc(func(c *http.Conn, req *http.Request) {}))
	http.Handle("/add", http.HandlerFunc(func(c *http.Conn, req *http.Request) {
		// Process the add template
		var buf bytes.Buffer
		/*    if err := parseerrorHTML.Execute(errors, &buf); err != nil {*/
		err := addHTML.Execute("x", &buf)
		if err != nil {
			log.Stderrf("addHTML.Execute: %s", err)
		}
		//templ.Execute(req.FormValue("s"), c);
		servePage(c, "Add", "", string(buf.Bytes()))
	}))
	http.Handle("/css/", http.FileServer("public/css", "/css/"))
	http.Handle("/js/", http.FileServer("public/js", "/js/"))

	err = http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
Exemple #26
0
func main() {
	runtime.GOMAXPROCS(2)

	log.Stdout("Starting basic HTTP server...\n")

	cwd, cwdErr := os.Getwd()
	if cwdErr != nil {
		fatalError(cwdErr.String())
	}

	tcp_listen_addr := &net.TCPAddr{net.IPv4(0, 0, 0, 0), 0}
	listener, listenErr := net.ListenTCP("tcp", tcp_listen_addr)

	if listenErr != nil {
		log.Stderr(listenErr.String())
	}
	log.Stdoutf("Listening on port: %s\n", listener.Addr().String())

	fsHandler := http.FileServer(cwd, "")
	http.Serve(listener, fsHandler)
	listener.Close()
	log.Stdout("Done.")
}
Exemple #27
0
// Create a new Roar from user input.
//
// Reads body of request tries to unmarshal a Roar from it. A lot of
// things can go wrong here *g*. A curl command that works is:
//
// $ curl -i -X POST -d \
// '{"Author":"Sven","Text":"Hello!!!!","CreationDate":"Sat, 10 Jul 2010 19:46:48 CEST"}' \
// -H "Content-Type: application/json" \
// http://localhost:9999/roars
//
func postRoarAsJson(ctx *web.Context) {
	log.Stderrf("Request:\n%v\n", ctx.Request)

	// read request body to buf
	var buf, err = ioutil.ReadAll(ctx.Request.Body)
	if nil != err {
		ctx.StartResponse(400)
		ctx.WriteString(err.String())
		return
	} else if 0 == len(buf) {
		ctx.StartResponse(400)
		ctx.WriteString("Empty request body.\n")
		return
	}
	log.Stderrf("Read %d bytes from Request.Body:", len(buf))
	log.Stderrf("\n%s\n", string(buf))

	// try unmarshal bytes and extract a Roar
	var r *Roar = &Roar{}
	err = json.Unmarshal(buf, r)
	if nil != err {
		ctx.StartResponse(400)
		ctx.WriteString(fmt.Sprintf("Couldn't parse input: %s\n",
			err.String()))
		return
	}

	// append new roar
	roarList.Push(r)
	log.Stdoutf("Created new Roar with id %d:\n%v\n",
		r, roarList.Len())

	//tell client id of new roar
	ctx.WriteString(fmt.Sprintf("Created new Roar with id: %d\n",
		roarList.Len()))
}
Exemple #28
0
func main() {
	flag.Parse() // parse command line args

	// setting twitter credentials
	creds.Username = *username
	creds.Password = *password
	creds.MaxFetchCount = *maxFetchCount

	// add handlers
	log.Stdout("Adding web handlers\n")
	http.Handle("/", http.HandlerFunc(HandleHome))
	http.Handle("/friend_tweets.json", http.HandlerFunc(HandleFriendTweetsJson))
	http.Handle("/update_status", http.HandlerFunc(HandleUpdateStatus))
	http.Handle("/foo", http.HandlerFunc(HandleFoo))

	// start web server
	log.Stdoutf("Starting web server: http://localhost:%d\nTo stop the server press Ctrl+C\n", *port)
	err := http.ListenAndServe(":"+strconv.Itoa(*port), nil)
	if err != nil {
		panic("ListenAndServe: %s\n", err.String())
	}

	log.Stdout("Server shutdown")
}
/**
 * GetFriendsTimeline gets the same timeline as Home does on the web. It uses the credentials
 * saved in the Client provided.
 */
func GetFriendsTimeline(client *Client) (statuses []Status, err os.Error) {
	log.Stdout("Get Friends Timeline\n")
	jsonStrResponse, err := GetFriendsTimelineJson(client)
	if err != nil {
		return nil, err
	}

	// parse json response
	var resultObj json.Json
	//log.Stdout("response: %s", jsonStrResponse);
	resultObj, err = parseJson(jsonStrResponse)
	if err != nil {
		return nil, err
	}

	// create status response
	var i int
	statuses = make([]Status, resultObj.Len())
	log.Stdoutf("result count: %d", resultObj.Len())
	for i = 0; i < len(statuses); i++ {
		statuses[i] = *parseStatus(resultObj.Elem(i))
	}
	return
}
Exemple #30
0
//runs the web application by serving fastcgi requests
func RunFcgi(addr string) {
	log.Stdoutf("web.go serving fcgi %s", addr)
	listenAndServeFcgi(addr)
}