Example #1
0
func readArgument(reader *bufio.Reader) ([]byte, error) {
	line, err := reader.ReadString('\n')
	if err != nil {
		return nil, Malformed("$<ArgumentLength>", line)
	}

	var argLength int
	if _, err := fmt.Sscanf(line, "$%d\r", &argLength); err != nil {
		return nil, Malformed("$<ArgumentLength>", line)
	}

	data, err := ioutil.ReadAll(io.LimitReader(reader, int64(argLength)))
	if err != nil {
		return nil, err
	}
	if len(data) != argLength {
		return nil, MalformedLength(argLength, len(data))
	}
	if b, err := reader.ReadByte(); err != nil || b != '\r' {
		return nil, MalformedMissingCRLF()
	}
	if b, err := reader.ReadByte(); err != nil || b != '\n' {
		return nil, MalformedMissingCRLF()
	}

	return data, nil
}
Example #2
0
// Read next line of text containing 2 numbers and return those two integers
func readNext2Ints(reader *bufio.Reader) (x int, y int) {
	line, _ := reader.ReadString('\n')
	row := strings.Split(strings.Trim(line, "\n"), " ")
	x, _ = strconv.Atoi(extractIntegerStr(row[0]))
	y, _ = strconv.Atoi(extractIntegerStr(row[1]))
	return
}
Example #3
0
func (c *InfoCommand) Decode(r *bufio.Reader) error {
	started := false
	for {
		resp, err := r.ReadString('\n')
		if err != nil {
			return err
		}

		// Handle the start condition
		if !started {
			switch resp {
			case "Set does not exist\n":
				c.done = true
				c.notExist = true
				return nil
			case "START\n":
				started = true
				c.notExist = false
				continue
			default:
				return fmt.Errorf("invalid response: %s", resp)
			}
		}

		// Check for the end
		if resp == "END\n" {
			c.done = true
			return nil
		}

		// Store the line
		c.lines = append(c.lines, resp)
	}
	return nil
}
Example #4
0
func readArgument(r *bufio.Reader) ([]byte, error) {

	line, err := r.ReadString('\n')
	if err != nil {
		return nil, malformed("$<argumentLength>", line)
	}
	var argSize int
	if _, err := fmt.Sscanf(line, "$%d\r", &argSize); err != nil {
		return nil, malformed("$<argumentSize>", line)
	}

	// I think int is safe here as the max length of request
	// should be less then max int value?
	data, err := ioutil.ReadAll(io.LimitReader(r, int64(argSize)))
	if err != nil {
		return nil, err
	}

	if len(data) != argSize {
		return nil, malformedLength(argSize, len(data))
	}

	// Now check for trailing CR
	if b, err := r.ReadByte(); err != nil || b != '\r' {
		return nil, malformedMissingCRLF()
	}

	// And LF
	if b, err := r.ReadByte(); err != nil || b != '\n' {
		return nil, malformedMissingCRLF()
	}

	return data, nil
}
Example #5
0
func readline(fi *bufio.Reader) (string, bool) {
	s, err := fi.ReadString('\n')
	if err != nil {
		return "", false
	}
	return s, true
}
Example #6
0
func main() {
	var conn net.Conn
	var error error
	var inputReader *bufio.Reader
	var input string
	var clientName string

	// maak connectie met de server:
	conn, error = net.Dial("tcp", "localhost:50000")
	checkError(error)

	inputReader = bufio.NewReader(os.Stdin)
	fmt.Println("First, what is your name?")
	clientName, _ = inputReader.ReadString('\n')
	// fmt.Printf("CLIENTNAME %s",clientName)
	trimmedClient := strings.Trim(clientName, "\r\n") // "\r\n" voor Windows, "\n" voor Linux

	for {
		fmt.Println("What to send to the server? Type Q to quit. Type SH to shutdown server.")
		input, _ = inputReader.ReadString('\n')
		trimmedInput := strings.Trim(input, "\r\n")
		// fmt.Printf("input:--%s--",input)
		// fmt.Printf("trimmedInput:--%s--",trimmedInput)
		if trimmedInput == "Q" {
			return
		}
		_, error = conn.Write([]byte(trimmedClient + " says: " + trimmedInput))
		checkError(error)
	}
}
Example #7
0
func Unpack(h *bufio.Reader) []byte {
	var enc, _ = h.ReadString('\n')
	enc = enc[0 : len(enc)-1] //chop newline: the docs are a lie
	var out []byte
	out, _ = base64.StdEncoding.DecodeString(enc)
	return out
}
Example #8
0
func createGroup(r *bufio.Reader, w *bufio.Writer, args []string, thisUser *utils.User) (err error) {

	if len(args) == 1 {
		fmt.Println("No arguments for call to create-group.")
		return nil
	}

	err = w.WriteByte(20)
	w.Flush()
	if err != nil {
		return err
	}

	// send the length of args
	err = w.WriteByte(uint8(len(args)))
	w.Flush()
	if err != nil {
		return err
	}

	for i := 1; i < len(args); i++ {

		// send group to create
		w.WriteString(args[i] + "\n")
		w.Flush()

		// get group id to display to user
		gid, _ := r.ReadString('\n')
		fmt.Println("Created group \"" + args[i] + "\" with id: " + strings.TrimSpace(gid))
	}
	// send the group to create

	return err
}
Example #9
0
func groupLs(r *bufio.Reader, w *bufio.Writer, args []string, thisUser *utils.User) (err error) {

	if len(args) != 2 {
		fmt.Println("Wrong number of arguments for call to group-ls:")
		fmt.Println("Format should be: group-ls GID")
		return nil
	}

	err = w.WriteByte(23)
	w.Flush()
	if err != nil {
		return err
	}

	// send the group id
	w.WriteString(args[1] + "\n")
	w.Flush()

	// get success (1) or fail (2)
	success, _ := r.ReadByte()
	if success != 1 {
		fmt.Println("The group does not exist")
		return err
	}

	// get uuids of the group
	result, _ := r.ReadString('\n')
	result = strings.TrimSuffix(strings.TrimSpace(result), ",")

	fmt.Println("Members of Group " + args[1] + ": " + result)

	return err
}
Example #10
0
// reads a bulk reply (i.e $5\r\nhello)
func readBulk(reader *bufio.Reader, head string) ([]byte, os.Error) {
	var err os.Error
	var data []byte

	if head == "" {
		head, err = reader.ReadString('\n')
		if err != nil {
			return nil, err
		}
	}

	if head[0] != '$' {
		return nil, RedisError("Expecting Prefix '$'")
	}

	size, err := strconv.Atoi(strings.TrimSpace(head[1:]))

	if size == -1 {
		return nil, RedisError("Key does not exist ")
	}
	lr := io.LimitReader(reader, int64(size))
	data, err = ioutil.ReadAll(lr)

	return data, err
}
Example #11
0
func readSection(reader *bufio.Reader, readN int) ([]byte, error) {
	buf := make([]byte, readN)

	var err error
	n := 0
	for n < readN {
		m, err := reader.Read(buf[n:])
		if err != nil {
			break
		}
		n += m
	}

	if err != nil {
		return buf, err
	}

	end, err := reader.ReadString('\n')
	switch {
	case n != readN:
		return buf, io.ErrUnexpectedEOF
	case err == io.EOF:
		// That's ok
	case err != nil:
		return buf, err
	case end != "\r\n":
		return buf, errors.New("Unexpected end of section")
	}
	return buf, nil
}
Example #12
0
func addMdns(controller *spotcontrol.SpircController, reader *bufio.Reader) {
	devices, err := controller.ListMdnsDevices()
	if err != nil {
		fmt.Println("Mdns devices can only be found when micro-controller is started \n" +
			"in discovery mode.  Restart without a username and password and with a --blobPath \n" +
			"argument (path where discovery blob will be saved) to start micro-controller in \n" +
			"disocvery mode \n")
		return
	}

	if len(devices) == 0 {
		fmt.Println("no devices found")
		return
	}
	fmt.Println("\n choose a device:")
	for i, d := range devices {
		fmt.Printf("%v) [mdns]%v %v \n", i, d.Name, d.Url)
	}
	var url string
	for {
		fmt.Print("Enter device number: ")
		text, _ := reader.ReadString('\n')
		i, err := strconv.Atoi(strings.TrimSpace(text))
		if err == nil && i < len(devices) && i >= 0 {
			url = devices[i].Url
			break
		}
		fmt.Println("invalid device number")
	}

	controller.ConnectToDevice(url)

}
Example #13
0
func readV1(bufRd *bufio.Reader) (*Header, error) {
	// magic "PROXY " has already been read
	line, err := bufRd.ReadString('\n')
	if err != nil {
		return nil, err
	}
	if !strings.HasSuffix(line, crlf) {
		return nil, ErrInvalidHeader
	}
	parts := strings.Split(line[:len(line)-2], " ")
	if len(parts) < 6 {
		return nil, ErrInvalidHeader
	}
	head := Header{Protocol: Protocol(parts[1])}
	if head.Protocol != TCP4 && head.Protocol != TCP6 {
		head.Protocol = UNKNOWN
	}
	if head.SrcAddr, err = parseAddress(head.Protocol, parts[2], parts[4]); err != nil {
		return nil, err
	}
	if head.DstAddr, err = parseAddress(head.Protocol, parts[3], parts[5]); err != nil {
		return nil, err
	}
	return &head, nil
}
Example #14
0
// For now just skips the header
func readHeader(infile *bufio.Reader) header {
	var hdr header
	for line, err := infile.ReadString('\n'); err == nil && !strings.HasPrefix(strings.ToLower(line), "@data"); line, err = infile.ReadString('\n') {
		line = strings.ToLower(line)
		match := attrRE.FindStringSubmatch(line)
		if match != nil {
			//This line is defining an attribute
			if len(match) < 3 {
				log.Fatalf("Invalid header on line:\n%s", line)
			}
			hdr.features.Push(match[1])
			continue
		}
		match = relRE.FindStringSubmatch(line)
		if match != nil {
			if hdr.name == "" {
				hdr.name = match[1]
			} else {
				log.Fatalf("Double declaration of relation name?\n"+
					"First: %s\n"+
					"Second: %s\n", hdr.name, match[1])
			}
		}
		//TODO: Need to do some parsing of header to create c50 files.
	}
	log.Printf("Read in %d attributes\n", len(hdr.features))
	return hdr
}
Example #15
0
func readNetString(rd *bufio.Reader) (rv string, err error) {
	lengthS, err := rd.ReadString(':')
	if err != nil {
		return "", err
	}

	lengthS = lengthS[0 : len(lengthS)-1]
	lengthS = strings.TrimSpace(lengthS)
	length, err := strconv.ParseUint(lengthS, 10, 16)
	if err != nil {
		return "", err
	}

	path := make([]byte, length+1)
	_, err = io.ReadFull(rd, path)
	if err != nil {
		return "", err
	}

	if lastCH := path[length]; lastCH != ',' {
		return "", fmt.Errorf("Expected , got %c", lastCH)
	}

	return string(path[:length]), nil
}
Example #16
0
// readCString reads one BSON C string. This is not a BSON element.
func readCstring(rd *bufio.Reader) (string, error) {
	s, err := rd.ReadString(0x00)
	if err != nil {
		return "", err
	}
	return s[:len(s)-1], nil
}
Example #17
0
// promptList prompts the user with the given prefix, list of valid responses,
// and default list entry to use.  The function will repeat the prompt to the
// user until they enter a valid response.
func promptList(reader *bufio.Reader, prefix string, validResponses []string, defaultEntry string) (string, error) {
	// Setup the prompt according to the parameters.
	validStrings := strings.Join(validResponses, "/")
	var prompt string
	if defaultEntry != "" {
		prompt = fmt.Sprintf("%s (%s) [%s]: ", prefix, validStrings,
			defaultEntry)
	} else {
		prompt = fmt.Sprintf("%s (%s): ", prefix, validStrings)
	}

	// Prompt the user until one of the valid responses is given.
	for {
		fmt.Print(prompt)
		reply, err := reader.ReadString('\n')
		if err != nil {
			return "", err
		}
		reply = strings.TrimSpace(strings.ToLower(reply))
		if reply == "" {
			reply = defaultEntry
		}

		for _, validResponse := range validResponses {
			if reply == validResponse {
				return reply, nil
			}
		}
	}
}
Example #18
0
File: eval.go Project: koji-m/yuyo
func ReadEvalPrintLoop(rdr *bufio.Reader) {
	m := newVM(topEnv)

	for {
		fmt.Print("yuyo> ")
		rcvStr := ""
		for {
			str, err := rdr.ReadString('\n')
			if err != nil {
				fmt.Println()
				return //maybe EOF, before '\n'
			}
			rcvStr += str
			retObj, readDone := readEval(rcvStr, m)
			if readDone {
				if retObj == yEOF {
					break
				}
				fmt.Println(extern(retObj))
				break
			}
			fmt.Print("      ")
		}
	}
}
Example #19
0
File: import.go Project: qgweb/new
func BulkInsertData(reader *bufio.Reader, ktype string) {
	bk := es.Bulk()
	num := 0
	for {
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		info := strings.Split(line, "\t#\t")
		log.Info(len(info))
		if len(info) != 2 {
			continue
		}
		ad, ua := getAdUa(info[0], "\t")
		keyword := getKeyWord(info[1], "\t")
		lonlat := GetLonLat(ad)
		if lonlat == "" {
			continue
		}
		num++
		id := encrypt.DefaultMd5.Encode("1456185600" + ad + ua)
		pinfo := map[string]interface{}{
			"ad":  ad,
			"ua":  ua,
			ktype: keyword,
			"geo": lonlat,
		}
		bk.Add(elastic.NewBulkUpdateRequest().Index("map_trace").Type("map").Doc(pinfo).Id(id).DocAsUpsert(true))
		bk.Add(elastic.NewBulkUpdateRequest().Index("map_trace_search").Type("map").Doc(pinfo).Id(id).DocAsUpsert(true))
		if num%10000 == 0 {
			log.Error(bk.Do())
		}
	}
	log.Info(bk.Do())
}
Example #20
0
func (c *ISOConfig) parseCheckSumFile(rd *bufio.Reader) error {
	errNotFound := fmt.Errorf("No checksum for %q found at: %s", filepath.Base(c.ISOUrls[0]), c.ISOChecksumURL)
	for {
		line, err := rd.ReadString('\n')
		if err != nil && line == "" {
			break
		}
		parts := strings.Fields(line)
		if len(parts) < 2 {
			continue
		}
		if strings.ToLower(parts[0]) == c.ISOChecksumType {
			// BSD-style checksum
			if parts[1] == fmt.Sprintf("(%s)", filepath.Base(c.ISOUrls[0])) {
				c.ISOChecksum = parts[3]
				return nil
			}
		} else {
			// Standard checksum
			if parts[1][0] == '*' {
				// Binary mode
				parts[1] = parts[1][1:]
			}
			if parts[1] == filepath.Base(c.ISOUrls[0]) {
				c.ISOChecksum = parts[0]
				return nil
			}
		}
	}
	return errNotFound
}
Example #21
0
File: main.go Project: ijt/aphid
// addHelp reads lines from a reader and prints them to stdout. It interjects
// helpful messages when those lines match patterns given by the config.
func addHelp(reader *bufio.Reader, conf *Config, prefix string) {
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			break
		}
		if line == "" {
			fmt.Fprintln(os.Stderr, "Line is null. Ending.")
			os.Exit(1)
		}
		fmt.Print(line)
		for _, rule := range conf.lineRules {
			matched := rule.patternRx.MatchString(line)
			if matched {
				pat := rule.patternRx
				res := []byte{}
				matches := pat.FindAllStringSubmatchIndex(line, -1)
				for _, submatchRange := range matches {
					msg := rule.message + "\n"
					res = pat.ExpandString(res, msg, line,
						submatchRange)
				}
				fmt.Print(prefix, " ", string(res))
			}
		}
	}
}
Example #22
0
func main() {
	var err error
	var reader *bufio.Reader
	var articles map[string][]articleType
	var article articleType

	reader = bufio.NewReader(os.Stdin)

	articles, err = fetchAllArticles()
	if err != nil {
		return
	}
	for {
		article, err = ncurses(articles)
		perror(err)
		if article == (articleType{}) {
			return
		}
		content, err := dlContent(article.url + "/ansi")
		perror(err)
		fmt.Println(content)
		fmt.Println("Press Enter to go back to the menu.")
		reader.ReadString('\n')
	}
}
Example #23
0
File: entry.go Project: vosst/csi
// NewEntry parses an entry from reader.
//
// Returns an error if reading from reader fails.
func NewEntry(reader bufio.Reader) (*Entry, error) {
	line, err := reader.ReadString('\n')
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Failed to parse line from reader [%s]", err))
	}

	entry := Entry{}
	if matches := dmesgLineRegExp.FindStringSubmatch(line); len(matches) >= 4 {
		if fl, err := strconv.Atoi(matches[dmesgSmFacLev]); err == nil {
			entry.Facility, entry.Level = facLev(uint(fl))
		}

		if s, err := strconv.Atoi(matches[dmesgSmTsSec]); err == nil {
			entry.When.Sec = int64(s)
		}

		if us, err := strconv.Atoi(matches[dmesgSmTsUsec]); err == nil {
			entry.When.Usec = int64(us)
		}

		entry.Message = matches[dmesgSmMsg]
	}

	return &entry, nil
}
Example #24
0
func readArgument(r *bufio.Reader) ([]byte, error) {

	line, err := r.ReadString('\n')
	if err != nil {
		return nil, malformed("$<argumentLength>", line)
	}
	var argSize int
	argSize, _ = strconv.Atoi(strings.Trim(line[1:], "\r\n"))
	if argSize == 0 {
		return nil, malformed("$<argumentSize>", line)
	}

	// I think int is safe here as the max length of request
	// should be less then max int value?
	data, err := ioutil.ReadAll(io.LimitReader(r, int64(argSize)))
	if err != nil {
		return nil, err
	}

	if len(data) != argSize {
		return nil, malformedLength(argSize, len(data))
	}
	tail, _ := r.ReadString('\n')
	if len(tail) <= 0 {
		return nil, malformedMissingCRLF()
	}

	return data, nil
}
Example #25
0
File: ini.go Project: barthy1/s3cli
func checkContinuationLines(buf *bufio.Reader, val string) (string, bool, error) {
	isEnd := false
	for {
		valLen := len(val)
		if valLen == 0 || val[valLen-1] != '\\' {
			break
		}
		val = val[:valLen-1]

		next, err := buf.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				return "", isEnd, err
			}
			isEnd = true
		}

		next = strings.TrimSpace(next)
		if len(next) == 0 {
			break
		}
		val += next
	}
	return val, isEnd, nil
}
Example #26
0
func tokenize(bf2 *bufio.Reader, bf3 *bufio.Writer) {
	for s, err := bf2.ReadString('\n'); err == nil; s, err = bf2.ReadString('\n') {
		fs := strings.Split(s, "\t")

		doc, _ := NewDocument(fs[0])
		doc.SetInput("T", fs[1])
		doc.SetInput("A", fs[2])
		doc.Tokenize()
		doc.AssembleSentences()

		var soffs []string
		sents := doc.SectionSentences("T")
		for _, sent := range sents {
			soffs = append(soffs, fmt.Sprintf("%d:%d", sent.Begin(), sent.End()))
		}
		bf3.WriteString(fmt.Sprintf("%s\t%s\t", fs[0], strings.Join(soffs, ",")))

		soffs = soffs[:0]
		sents = doc.SectionSentences("A")
		for _, sent := range sents {
			soffs = append(soffs, fmt.Sprintf("%d:%d", sent.Begin(), sent.End()))
		}
		bf3.WriteString(fmt.Sprintf("%s\n", strings.Join(soffs, ",")))
	}
}
Example #27
0
func (c *ListCommand) Decode(r *bufio.Reader) error {
	started := false
	for {
		resp, err := r.ReadString('\n')
		if err != nil {
			return err
		}

		// Handle the start condition
		if !started {
			if resp != "START\n" {
				return fmt.Errorf("expect list start block")
			}
			started = true
			continue
		}

		// Check for the end
		if resp == "END\n" {
			c.done = true
			return nil
		}

		// Store the line
		c.lines = append(c.lines, resp)
	}
	return nil
}
Example #28
0
func getDataFromfile(fileName string) string {

	var inputFile *os.File
	var inputError error
	var readerError error
	var inputReader *bufio.Reader
	var inputString string
	var readenString string

	inputFile, inputError = os.OpenFile(fileName, os.O_RDONLY, 0)

	if inputError != nil {
		fmt.Printf("Error opening file")
		return "Error opening file"
	}

	inputReader = bufio.NewReader(inputFile)

	for {

		readenString, readerError = inputReader.ReadString(';')
		if readerError != nil {

			break
		}

		inputString += readenString

	}
	return inputString
}
Example #29
0
// reads a bulk reply (i.e $5\r\nhello)
func readBulk(reader *bufio.Reader, head string) ([]byte, error) {
	var err error
	var data []byte

	if head == "" {
		head, err = reader.ReadString('\n')
		if err != nil {
			return nil, err
		}
	}
	switch head[0] {
	case ':':
		data = []byte(strings.TrimSpace(head[1:]))

	case '$':
		size, err := strconv.Atoi(strings.TrimSpace(head[1:]))
		if err != nil {
			return nil, err
		}
		if size == -1 {
			return nil, doesNotExist
		}
		lr := io.LimitReader(reader, int64(size))
		data, err = ioutil.ReadAll(lr)
		if err == nil {
			// read end of line
			_, err = reader.ReadString('\n')
		}
	default:
		return nil, RedisError("Expecting Prefix '$' or ':'")
	}

	return data, err
}
Example #30
0
func firstRun(r *bufio.Reader) {
	fmt.Println("Welcome to the chat server. Please type your desired alias")
	line, _ := r.ReadString('\n')
	// Send the correct alias and log him in
	line = "/nick " + line
	handleUserInput(line)

	// FIXME This doesn't check login errors
	fmt.Println("You are now on the server")
	fmt.Println("The current temperature is")
	b := make(chan string, 1)
	b <- weather.GetStringWeather("Guadalajara")
	var res string
	select {
	case s := <-b:
		res = s
	case <-time.After(5 * time.Second):
		res = "Timeout"
	}
	fmt.Println(res)
	fmt.Println("This is a list of command available")
	line = "/help"
	handleUserInput(line)
	fmt.Println()
}