Example #1
0
func failnoting(s string, e os.Error) {
	if e != nil {
		fmt.Println(Usage())
		fmt.Println("\n"+s, e.String())
		os.Exit(1)
	}
}
Example #2
0
func main() {

	var err os.Error

	db := 0
	port := 6379

	args := os.Args[1:]

	for i := 0; i < len(args); i++ {
		arg := args[i]
		if arg == "-p" && i < len(args)-1 {
			if port, err = strconv.Atoi(args[i+1]); err != nil {
				println(err.String())
				return
			}
			i += 1
			continue
		} else if arg == "-db" && i < len(args)-1 {
			if db, err = strconv.Atoi(args[i+1]); err != nil {
				println(err.String())
				return
			}
			i += 1
			continue
		} else {
			println("Invalid argument: ", arg)
			usage()
			return
		}
	}
	println("port", port, db)
	load_db(port, db, bufio.NewReader(os.Stdin))

}
Example #3
0
func (n *Network) Pass() os.Error {
	t := strconv.Itoa64(time.Nanoseconds())
	myreplies := []string{"ERR_NEEDMOREPARAMS", "ERR_ALREADYREGISTRED"}
	var err os.Error
	repch := make(chan *IrcMessage)
	for _, rep := range myreplies {
		if err := n.Listen.RegListener(replies[rep], t, repch); err != nil {
			err = os.NewError(fmt.Sprintf("Couldn't authenticate with password, exiting: %s", err.String()))
		}
	}
	ticker := time.NewTicker(timeout(n.lag))
	defer func(myreplies []string, t string, tick *time.Ticker) {
		for _, rep := range myreplies {
			n.Listen.DelListener(replies[rep], t)
		}
		tick.Stop()
		return
	}(myreplies, t, ticker)
	n.queueOut <- &IrcMessage{"", "PASS", []string{n.password}}
	select {
	case msg := <-repch:
		if msg.Cmd == replies["ERR_NEEDMOREPARAMS"] {
			err = os.NewError(fmt.Sprintf("Need more parameters for password: %s", msg.String()))
		}
		break
	case <-ticker.C:
		break
	}
	return err
}
Example #4
0
func NewStore(dir string, depth int, before int64) *BitcaskStore {
	p := new(BitcaskStore)
	p.depth = depth
	p.before = before
	p.locks = make([]sync.Mutex, 97)

	count := 1 << uint32(depth*4)
	p.bc = make([]*htree.Bitcask, count)
	for i := 0; i < count; i++ {
		subdir := ""
		if depth > 0 {
			sf := fmt.Sprintf("%%0%dx", depth)
			subdir = fmt.Sprintf(sf, i)
			subdir = strings.Join(strings.Split(subdir, ""), "/")
		}
		dbpath := path.Join(dir, subdir)
		os.MkdirAll(dbpath, 0755)
		var err os.Error
		p.bc[i], err = htree.NewBitcask(dbpath, depth, before)
		if err != nil {
			panic(os.NewError("Can not open db:" + dbpath + err.String()))
		}
	}

	return p
}
Example #5
0
func addWidget(w http.ResponseWriter, r *http.Request) {
	var err os.Error
	if fixup == nil {
		fixup, err = regexp.Compile(`[^A-Za-z0-9\-_. ]`)
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
	}

	ctx := appengine.NewContext(r)
	name := fixup.ReplaceAllString(r.FormValue("name"), "")

	if len(name) == 0 {
		http.Error(w, "Invalid/no name provided", http.StatusInternalServerError)
		return
	}

	widget := NewWidget(ctx, name)

	err = widget.Commit()
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/widget/list", http.StatusFound)
}
func match(t *testing.T, err os.Error, pat string) bool {
	ok, err1 := regexp.MatchString(pat, err.String())
	if err1 != nil {
		t.Fatalf("compile regexp %s: %v", pat, err1)
	}
	return ok
}
Example #7
0
File: abort.go Project: 8l/go-learn
// Abort aborts the thread's current computation,
// causing the innermost Try to return err.
func (t *Thread) Abort(err os.Error) {
	if t.abort == nil {
		panicln("abort:", err.String())
	}
	t.abort <- err
	runtime.Goexit()
}
Example #8
0
func print(a interface{}, err os.Error) {
	if err == nil {
		fmt.Printf("  answer: %v\r\n", a)
	} else if err != ErrCtrlD {
		fmt.Printf(err.String() + "\r\n")
	}
}
Example #9
0
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")

}
Example #10
0
func error(t *testing.T, err os.Error, msg string) {
	if err == nil {
		t.Error(msg)
	} else {
		t.Errorf("%s: %s\n", msg, err.String())
	}
}
Example #11
0
func checkErr(message string, err os.Error) {
	// ignore os.EOF since it's not really an error...
	if err != nil && err != os.EOF {
		os.Stderr.WriteString(message + "\n" + err.String() + "\n")
		os.Exit(1)
	}
}
Example #12
0
File: fcgi.go Project: ality/web.go
func (s *Server) listenAndServeFcgi(addr string) os.Error {
	var l net.Listener
	var err os.Error

	//if the path begins with a "/", assume it's a unix address
	if strings.HasPrefix(addr, "/") {
		l, err = net.Listen("unix", addr)
	} else {
		l, err = net.Listen("tcp", addr)
	}

	if err != nil {
		s.Logger.Println("FCGI listen error", err.String())
		return err
	}
	for {
		fd, err := l.Accept()
		if err != nil {
			s.Logger.Println("FCGI accept error", err.String())
			break
		}
		go s.handleFcgiConnection(fd)
	}
	return nil
}
Example #13
0
func (vr *VerifyRequest) VerifySignature() bool {
	armorData := reArmor(vr.CamliSig)
	block, _ := armor.Decode(bytes.NewBufferString(armorData))
	if block == nil {
		return vr.fail("can't parse camliSig armor")
	}
	var p packet.Packet
	var err os.Error
	p, err = packet.Read(block.Body)
	if err != nil {
		return vr.fail("error reading PGP packet from camliSig: " + err.String())
	}
	sig, ok := p.(*packet.Signature)
	if !ok {
		return vr.fail("PGP packet isn't a signature packet")
	}
	if sig.Hash != crypto.SHA1 && sig.Hash != crypto.SHA256 {
		return vr.fail("I can only verify SHA1 or SHA256 signatures")
	}
	if sig.SigType != packet.SigTypeBinary {
		return vr.fail("I can only verify binary signatures")
	}
	hash := sig.Hash.New()
	hash.Write(vr.bp) // payload bytes
	err = vr.PublicKeyPacket.VerifySignature(hash, sig)
	if err != nil {
		return vr.fail(fmt.Sprintf("bad signature: %s", err))
	}
	vr.SignerKeyId = vr.PublicKeyPacket.KeyIdString()
	return true
}
Example #14
0
// Sends messages over the remote conn that come through the queue.
func (cl *client) SendLoop(cs chan<- Msg) {
	defer logAndClose(cl.conn)
	for {
		msg := <-cl.SendQueue
		var err os.Error
		switch m := msg.(type) {
		case MsgAddEntity:
			err = sendMessage(cl.conn, makeAddEntity(int32(m.Uid), m.Name))
		case MsgRemoveEntity:
			err = sendMessage(cl.conn, makeRemoveEntity(int32(m.Uid), m.Name))
		case MsgUpdateState:
			value := packState(m.State)
			err = sendMessage(cl.conn, makeUpdateState(int32(m.Uid), m.State.Name(), value))
		case MsgAssignControl:
			err = sendMessage(cl.conn, makeAssignControl(int32(m.Uid), m.Revoked))
		case MsgEntityDeath:
			uid, name := m.Entity.Uid, m.Entity.Name
			kuid, kname := m.Killer.Uid, m.Killer.Name
			err = sendMessage(cl.conn, makeEntityDeath(int32(uid), name, int32(kuid), kname))
		case MsgCombatHit:
			auid, aname := m.Attacker.Uid, m.Attacker.Name
			vuid, vname := m.Victim.Uid, m.Victim.Name
			err = sendMessage(cl.conn, makeCombatHit(int32(auid), aname, int32(vuid), vname, m.Damage))
		}
		// Remove client if something went wrong
		if err != nil {
			cs <- removeClientMsg{cl, "Sending message to client failed: " + err.String()}
			return
		}
	}
}
Example #15
0
// parse a file, and store the templates in Page.Template
func (t *Page) ParseFile(formatterMap map[string]func(io.Writer, string, ...interface{})) {
	var err os.Error
	t.Template, err = template.ParseFile(t.Filename, formatterMap)
	if err != nil {
		log.Fatal("Cannot Parse " + t.Filename + "; got " + err.String())
	}
}
Example #16
0
func (s *Server) listenAndServeScgi(addr string) os.Error {

	var l net.Listener
	var err os.Error

	//if the path begins with a "/", assume it's a unix address
	if strings.HasPrefix(addr, "/") {
		l, err = net.Listen("unix", addr)
	} else {
		l, err = net.Listen("tcp", addr)
	}

	//save the listener so it can be closed
	s.l = l

	if err != nil {
		s.Logger.Println("SCGI listen error", err.String())
		return err
	}

	for {
		fd, err := l.Accept()
		if err != nil {
			s.Logger.Println("SCGI accept error", err.String())
			return err
		}
		go s.handleScgiRequest(fd)
	}
	return nil
}
Example #17
0
// Keep on writing outgoing messages to the socket
func (conn *Conn) sending() {
	for p := range conn.out {
		if p == nil {
			conn.Err <- ErrNilPacket
			continue
		}

		var err os.Error
		if p.Addr == nil {
			if !conn.IsConnected() {
				conn.error("conn.sending(): [%s] %s", p.Addr.String(), ErrClosedConn.String())
				continue
			}

			if _, err = conn.sock.Write(p.Msg); err != nil {
				conn.error("conn.sending(): %s", err.String())
			}
		} else {
			if !conn.IsConnected() {
				conn.error("conn.sending(): %s", ErrClosedConn.String())
				continue
			}

			if _, err = conn.sock.WriteTo(p.Msg, p.Addr); err != nil {
				conn.error("conn.sending() [%s]: %s", p.Addr.String(), err.String())
			}
		}
		if err != nil {
			conn.Disconnect()
			break
		}

	}
}
Example #18
0
// Test that when we open a real XLSX file we create xlsx.Sheet
// objects for the sheets inside the file and that these sheets are
// themselves correct.
func TestCreateSheet(t *testing.T) {
	var xlsxFile *File
	var error os.Error
	var sheet *Sheet
	var row *Row
	xlsxFile, error = OpenFile("testfile.xlsx")
	if error != nil {
		t.Error(error.String())
		return
	}
	if xlsxFile == nil {
		t.Error("OpenFile returned a nil File pointer but did not generate an error.")
		return
	}
	if len(xlsxFile.Sheets) == 0 {
		t.Error("Expected len(xlsxFile.Sheets) > 0")
		return
	}
	sheet = xlsxFile.Sheets[0]
	if len(sheet.Rows) != 2 {
		t.Error("Expected len(sheet.Rows) == 2")
		return
	}
	row = sheet.Rows[0]
	if len(row.Cells) != 2 {
		t.Error("Expected len(row.Cells) == 2")
		return
	}
	cell := row.Cells[0]
	cellstring := cell.String()
	if cellstring != "Foo" {
		t.Error("Expected cell.String() == 'Foo', got ", cellstring)
	}
}
Example #19
0
func TestBasic(t *testing.T) {

	var val []byte
	var err os.Error

	err = client.Set("a", []byte("hello"))

	if err != nil {
		t.Fatal("set failed", err.String())
	}

	if val, err = client.Get("a"); err != nil || string(val) != "hello" {
		t.Fatal("get failed")
	}

	if typ, err := client.Type("a"); err != nil || typ != "string" {
		t.Fatal("type failed", typ)
	}

	//if keys, err := client.Keys("*"); err != nil || len(keys) != 1 {
	//    t.Fatal("keys failed", keys)
	//}

	client.Del("a")

	if ok, _ := client.Exists("a"); ok {
		t.Fatal("Should be deleted")
	}
}
Example #20
0
func main() {

	var err os.Error

	// Pull in command line options or defaults if none given
	flag.Parse()

	f, err := os.OpenFile(*skylib.LogFileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err == nil {
		defer f.Close()
		log.SetOutput(f)
	}

	skylib.Setup(sName)

	homeTmpl = template.MustParse(homeTemplate, nil)
	respTmpl = template.MustParse(responseTemplate, nil)

	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/new", submitHandler)

	rpc.HandleHTTP()

	portString := fmt.Sprintf("%s:%d", *skylib.BindIP, *skylib.Port)

	err = http.ListenAndServe(portString, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.String())
	}
}
Example #21
0
func match(t *testing.T, err os.Error, pat string) bool {
	ok, errstr := testing.MatchString(pat, err.String())
	if errstr != "" {
		t.Fatalf("compile regexp %s: %v", pat, errstr)
	}
	return ok
}
Example #22
0
func myWidgets(w http.ResponseWriter, r *http.Request) {
	var err os.Error
	ctx := appengine.NewContext(r)

	page, err := template.Parse(myWidgetTemplate, nil)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	data := myWidgetData{
		CSS:    commonCSS(),
		Header: header(ctx),
	}

	data.Widget, err = LoadWidgets(ctx)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	if len(r.FormValue("ids_only")) > 0 {
		w.Header().Set("Content-Type", "text/plain")
		for _, widget := range data.Widget {
			fmt.Fprintln(w, widget.ID)
		}
		return
	}

	page.Execute(w, data)
}
Example #23
0
func MakeRedirect(base string) (handler func(ctx *web.Context, val string)) {
	handler = func(ctx *web.Context, val string) {
		var fin *os.File
		var err os.Error
		fin, err = os.Open(path.Join(base, val), os.O_RDONLY, 0)
		if err != nil {
			ctx.WriteString(err.String())
			return
		}
		buf := make([]byte, 1024)
		for {
			var n int
			n, err = fin.Read(buf)
			if err != nil {
				ctx.WriteString(err.String())
				return
			}
			if n == 0 || err != nil {
				break
			}
			ctx.Write(buf[0:n])
		}
		fin.Close()
	}
	return
}
Example #24
0
func DoozerConnect() {
	var err os.Error
	DC, err = doozer.Dial(*DoozerServer)
	if err != nil {
		log.Panic(err.String())
	}
}
Example #25
0
func (mw *MainWindow) showError(err os.Error) {
	if err == nil {
		return
	}

	walk.MsgBox(mw, "Error", err.String(), walk.MsgBoxOK|walk.MsgBoxIconError)
}
Example #26
0
File: goplay.go Project: ssrl/go
// error writes compile, link, or runtime errors to the HTTP connection.
// The JavaScript interface uses the 404 status code to identify the error.
func error(w http.ResponseWriter, out []byte, err os.Error) {
	w.WriteHeader(404)
	if out != nil {
		output.Execute(w, out)
	} else {
		output.Execute(w, err.String())
	}
}
Example #27
0
func Errored(e os.Error, mesg string) bool {
	if e != nil {
		fmt.Printf("Errored %s\n", mesg)
		fmt.Println(e.String())
		return true
	}
	return false
}
Example #28
0
func init() {
	// command-line flags
	track = flag.String("track", "", "comma-separated list of tracking terms")
	thresh = flag.Float64("thresh", DefaultThresh, "the confidence threshold required to learn new content")
	exclList = flag.String("exclude", "", "comma-separated list of keywords excluded from classification")
	printOnly = flag.Bool("print-only", false, "only print the Tweets, do not classify them")
	loadFile = flag.String("load-file", "", "specify classifier file")
	flag.Parse()

	// read the arguments
	args := flag.Args()
	if len(args) != 2 {
		println("Usage: [--help|<options>...] <username> <password>")
		os.Exit(1)
	}
	username = args[0]
	password = args[1]

	// load and train the classifier
	if *loadFile != "" {
		// from a file
		var err os.Error
		c, err = NewClassifierFromFile(*loadFile)
		if err != nil {
			println("error loading:", err.String())
			os.Exit(1)
		}
		fmt.Fprintf(os.Stderr, "classifier is loaded: %v\n", c.WordCount())
	} else {
		// from scratch
		c = NewClassifier(Positive, Negative)
		LearnFile(c, "data/positive.txt", Positive)
		LearnFile(c, "data/negative.txt", Negative)
		fmt.Fprintf(os.Stderr, "classifier is trained: %v\n", c.WordCount())
	}

	// init the sanitizer
	excl := strings.Split(*exclList, ",")
	if *exclList != "" {
		fmt.Fprintf(os.Stderr, "excluding: %v\n", excl)
	}
	stopWords := ReadFile("data/stopwords.txt")
	fmt.Fprintf(os.Stderr, "stop words: %v\n", stopWords)
	san = NewSanitizer(
		ToLower,
		NoMentions,
		NoLinks,
		NoNumbers,
		Punctuation,
		NoSmallWords,
		CombineNots,
		Exclusions(excl),
		Exclusions(stopWords),
	)

	// listen for Ctrl-C
	go signalHandler()
}
Example #29
0
func serveError(req *web.Request, status int, reason os.Error, header web.Header) {
	header.Set(web.HeaderContentType, "text/plain; charset=utf-8")
	w := req.Responder.Respond(status, header)
	io.WriteString(w, web.StatusText(status))
	if reason != nil {
		io.WriteString(w, "\n")
		io.WriteString(w, reason.String())
	}
}
Example #30
0
func (p *MockGoogleClient) AddMockGroupJSONEntry(s string) {
	c := new(GroupResponse)
	var err os.Error
	if err = json.Unmarshal([]byte(s), c); err == nil {
		p.AddMockGroup(c.Entry)
	} else {
		fmt.Printf("error adding mock group json entry: %s\n\n", err.String())
	}
}