// Symbol looks up the program counters listed in the request, // responding with a table mapping program counters to function names. // The package initialization registers it as /debug/pprof/symbol. func Symbol(c *http.Conn, r *http.Request) { c.SetHeader("content-type", "text/plain; charset=utf-8") // We don't know how many symbols we have, but we // do have symbol information. Pprof only cares whether // this number is 0 (no symbols available) or > 0. fmt.Fprintf(c, "num_symbols: 1\n") var b *bufio.Reader if r.Method == "POST" { b = bufio.NewReader(r.Body) } else { b = bufio.NewReader(strings.NewReader(r.URL.RawQuery)) } for { w, err := b.ReadSlice('+') if err == nil { w = w[0 : len(w)-1] // trim + } pc, _ := strconv.Btoui64(string(w), 0) if pc != 0 { f := runtime.FuncForPC(uintptr(pc)) if f != nil { fmt.Fprintf(c, "%#x %s\n", pc, f.Name()) } } // Wait until here to check for err; the last // symbol will have an err because it doesn't end in +. if err != nil { break } } }
func main() { // connect to server conn, err := net.Dial("tcp", ":15440") if err != nil { fmt.Fprintf(os.Stderr, "Error connecting to port 15440: %v\n", err) os.Exit(1) } for { // get message from stdin fmt.Println("Say something: ") message, err := bufio.NewReader(os.Stdin).ReadString('\n') if err != nil { fmt.Fprintf(os.Stderr, "Error reading from stdin: %v\n", err) os.Exit(1) } // send message to server fmt.Fprintf(conn, "%v\n", message) // receive message from server message, err = bufio.NewReader(conn).ReadString('\n') if err != nil { fmt.Fprintf(os.Stderr, "Error reading from server: %v\n", err) os.Exit(1) } // print server message to Stdout fmt.Fprintf(os.Stdout, "%v\n", message) } }
func dsInTxt(c *cmdapp.Command, fname string) { var in *bufio.Reader if len(fname) > 0 { f, err := os.Open(fname) if err != nil { fmt.Fprintf(os.Stderr, "%s\n", c.ErrStr(err)) return } defer f.Close() in = bufio.NewReader(f) } else { in = bufio.NewReader(os.Stdin) } for { tn, err := readLine(in) if err != nil { break } ln := strings.Join(tn, " ") set := &jdh.Dataset{ Title: ln, } id, err := localDB.Exec(jdh.Add, jdh.Datasets, set) if err != nil { fmt.Fprintf(os.Stderr, "%s\n", c.ErrStr(err)) continue } if verboseFlag { fmt.Fprintf(os.Stdout, "%s %s\n", id, set.Title) } } }
// waiter is a function that waits for any messages received by the connection to the server. // When a message comes in, the screen will be re-rendered. func waiter(connection net.Conn) { rawMessage, err := bufio.NewReader(connection).ReadString('\x04') loop: for err == nil { mutex.Lock() message := rawMessage[1 : len(rawMessage)-1] switch rawMessage[0] { case '\x00': printer.run = false message = strings.Replace(message, "\x1f", ": ", 2) clientSettings.messageList = append(clientSettings.messageList, message) printer.printMessages() case '\x01': clientSettings.messageList = append(clientSettings.messageList, "[ "+message+" says hi :) ]") case '\x02': clientSettings.messageList = append(clientSettings.messageList, "[ "+message+" says bye :( ]") case '\x03': clientSettings.messageList = append(clientSettings.messageList, "[ SERVER: "+message+" ]") break loop } mutex.Unlock() rawMessage, err = bufio.NewReader(connection).ReadString('\x04') } printer.printMessages() printer.run = false if err != nil { fmt.Println("ERROR: Connection to server lost.") } cleanup(connection) }
func TestStarRequest(t *testing.T) { req, err := ReadRequest(bufio.NewReader(strings.NewReader("M-SEARCH * HTTP/1.1\r\n\r\n"))) if err != nil { return } var out bytes.Buffer if err := req.Write(&out); err != nil { t.Fatal(err) } back, err := ReadRequest(bufio.NewReader(&out)) if err != nil { t.Fatal(err) } // Ignore the Headers (the User-Agent breaks the deep equal, // but we don't care about it) req.Header = nil back.Header = nil if !reflect.DeepEqual(req, back) { t.Errorf("Original request doesn't match Request read back.") t.Logf("Original: %#v", req) t.Logf("Original.URL: %#v", req.URL) t.Logf("Wrote: %s", out.Bytes()) t.Logf("Read back (doesn't match Original): %#v", back) } }
func TestHandling(t *testing.T) { cn, err := net.Dial("tcp", "localhost:3636") if err != nil { fmt.Println(err) t.FailNow() } shortMsg := "%d gameStart\n" longMsg := "%d gotta type a very long message such that it is over 100 chars such that it will detect it as being a GameEnd event\n" for i := 0; i < 2; i++ { _, err := cn.Write([]byte(fmt.Sprintf(shortMsg, i))) if err != nil { fmt.Println(err) } _, err = bufio.NewReader(cn).ReadString('\n') if err != nil { fmt.Println(err) } _, err = cn.Write([]byte(fmt.Sprintf(longMsg, i))) if err != nil { fmt.Println(err) } _, err = bufio.NewReader(cn).ReadString('\n') if err != nil { fmt.Println(err) } } cn.Close() }
// Dial connects to server at address func (handler *ConnHandler) Dial(addr string) ([]Peer, error) { var peers []Peer conn, err := net.Dial("tcp", addr) if err != nil { log.Println(err) return nil, err } writer := bufio.NewWriter(conn) reader := bufio.NewReader(conn) line, _ := reader.ReadString('\n') line = strings.Trim(line, "\n") addrs := strings.Split(line, ";") info := strings.Split(addrs[0], ",") writer.WriteString(handler.String() + "\n") writer.Flush() peers = append(peers, NewPeer(conn, conn, info[0], info[1])) for _, a := range addrs[1:] { info := strings.Split(a, ",") c, _ := net.Dial("tcp", info[0]) writer = bufio.NewWriter(c) writer.WriteString(handler.String() + "\n") writer.Flush() reader = bufio.NewReader(c) line, _ = reader.ReadString('\n') peers = append(peers, NewPeer(c, c, info[0], info[1])) } return peers, nil }
func TestServeHTTPReadRequestError(t *testing.T) { p := NewProxy(mitm) // Shorten the timeout to force a ReadRequest error. p.Timeout = time.Second rc, wc := pipeWithTimeout() defer rc.Close() defer wc.Close() rw := newHijackRecorder(wc) req, err := http.NewRequest("CONNECT", "//www.example.com:443", nil) if err != nil { t.Fatalf("http.NewRequest(): got %v, want no error", err) } go p.ServeHTTP(rw, req) res, err := http.ReadResponse(bufio.NewReader(rc), req) if err != nil { t.Fatalf("http.ReadResponse(): got %v, want no error", err) } res.Body.Close() tlsConn := tlsClient(rc, p.mitm.Authority, "www.example.com") tlsConn.Write([]byte("INVALID /invalid NOTHTTP/1.1\r\n")) if _, err = http.ReadResponse(bufio.NewReader(tlsConn), nil); err != io.ErrUnexpectedEOF { t.Fatalf("http.ReadResponse(): got %v, want io.ErrUnexpectedEOF", err) } }
func (t *Testbed) Start() { t.mu.Lock() defer t.mu.Unlock() if t.pipe != nil { return } t.pipe = exec.Command(t.cmd, t.args...) w, err := t.pipe.StdinPipe() if err != nil { panic(err) } t.apiWrite = bufio.NewWriter(w) r, err := t.pipe.StdoutPipe() if err != nil { panic(err) } t.apiRead = bufio.NewReader(r) r, err = t.pipe.StderrPipe() if err != nil { panic(err) } t.apiErr = bufio.NewReader(r) if err := t.pipe.Start(); err != nil { panic(err) } }
/** * Load and process the api blueprint file to get the endpoints, * requests and responses */ func ProcessApiBlueprintTest(filepath string) map[string]string { bpm := make(map[string]string) apibfile, err := os.Open("blueprint/test_buyers.json") if err != nil { fmt.Printf("error opening file: %v\n", err) os.Exit(1) } var outputmock string reader := bufio.NewReader(apibfile) line, e := Readln(reader) for e == nil { outputmock += line line, e = Readln(reader) } bpm["/crm-api/v1.0/buyers"] = outputmock apibfile, err = os.Open("blueprint/test_purchases.json") if err != nil { fmt.Printf("error opening file: %v\n", err) os.Exit(1) } reader = bufio.NewReader(apibfile) line, e = Readln(reader) for e == nil { outputmock += line line, e = Readln(reader) } bpm["/crm-api/v1.0/purchases"] = outputmock return bpm }
func main() { flag.StringVar(&in, "i", "", "input file (*.apib)") flag.Parse() if in == "" { fmt.Println("no input file provided. usage: -i input.apib") os.Exit(1) } f, err := os.Open(in) if err != nil { fmt.Printf("error while opening file %s: %v\n", in, err) os.Exit(1) } defer f.Close() rd := bufio.NewReader(f) input, err := ioutil.ReadAll(rd) if err != nil { fmt.Printf("error while reading file %s: %v\n", in, err) os.Exit(1) } errorCode := 0 b, err := godrafter.DrafterParse(input, 0) if err != nil { fmt.Printf("error while parsing: %v\n", err) errorCode = 1 } if b != nil { rd = bufio.NewReader(bytes.NewReader(b)) _, err = io.Copy(os.Stdout, rd) if err != nil { fmt.Printf("io error: %v\n", err) errorCode = 2 } } os.Exit(errorCode) }
// handleConn processes conn. This is run in a separate goroutine. func (s *Service) handleConn(conn net.Conn) { defer s.statMap.Add(statConnectionsActive, -1) s.statMap.Add(statConnectionsActive, 1) s.statMap.Add(statConnectionsHandled, 1) // Read header into buffer to check if it's HTTP. var buf bytes.Buffer r := bufio.NewReader(io.TeeReader(conn, &buf)) // Attempt to parse connection as HTTP. _, err := http.ReadRequest(r) // Rebuild connection from buffer and remaining connection data. bufr := bufio.NewReader(io.MultiReader(&buf, conn)) conn = &readerConn{Conn: conn, r: bufr} // If no HTTP parsing error occurred then process as HTTP. if err == nil { s.statMap.Add(statHTTPConnectionsHandled, 1) s.httpln.ch <- conn return } // Otherwise handle in telnet format. s.wg.Add(1) s.handleTelnetConn(conn) }
func ReadBinlog(reader io.Reader) (err error) { c := &proto.BufReader{Reader: bufio.NewReader(reader)} buf := &bytes.Buffer{} r := &proto.BufReader{Reader: bufio.NewReader(buf)} tmp := make([]byte, 4) _, err = c.Read(tmp) if err != nil { return } // http://dev.mysql.com/doc/internals/en/binlog-file-header.html if bytes.Compare(tmp, []byte{0xfe, 0x62, 0x69, 0x6e}) != 0 { err = ErrFileHeader return } h := &EventHeader{} h.Read(c) spew.Dump(h) _, err = io.CopyN(buf, c, int64(h.EventSize)) if err != nil { panic(err) } f := &FormatDescriptionEvent{} f.Read(r) spew.Dump(f) return }
func test() { cmd := exec.Command("/usr/local/bin/python", "test.py") outPipe, err := cmd.StdoutPipe() if err != nil { fmt.Println(err) } errPipe, err := cmd.StderrPipe() if err != nil { fmt.Println(err) } outBuf := bufio.NewReader(outPipe) errBuf := bufio.NewReader(errPipe) go stdOut(outBuf) go stdErr(errBuf) err = cmd.Start() if err != nil { fmt.Println(err) return } fmt.Println(cmd.Process.Pid) defer cmd.Process.Kill() defer cmd.Process.Release() cmd.Wait() }
func bodyDiff(win *acme.Win, ffile string) (bool, error) { tf, err := os.Open(ffile) if err != nil { return false, err } defer tf.Close() win.Seek("body", 0, 0) fr := bufio.NewReader(tf) br := bufio.NewReader(&bodyReader{win}) for { fb, errf := fr.ReadByte() if errf != nil && errf != io.EOF { return false, errf } bb, errb := br.ReadByte() if errb != nil && errb != io.EOF { return false, errb } if fb != bb { return true, nil } if errf == io.EOF && errb == io.EOF { return false, nil } } }
func main() { // listen for connections if ln, err := net.Listen("tcp", ":8080"); err == nil { for { // accept connections if conn, err := ln.Accept(); err == nil { reader := bufio.NewReader(conn) // read requests from the client if req, err := http.ReadRequest(reader); err == nil { // connect to the backend web server if be, err := net.Dial("tcp", "127.0.0.1:8081"); err == nil { be_reader := bufio.NewReader(be) // send the request to the backend if err := req.Write(be); err == nil { // read the response from the backend if resp, err := http.ReadResponse(be_reader, req); err == nil { // send the response to the client, making sure to close it resp.Close = true if err := resp.Write(conn); err == nil { log.Printf("proxied %s: got %d", req.URL.Path, resp.StatusCode) } conn.Close() // loop back to accepting the next connection } } } } } } } }
func (tbx *Bix) Query(region interfaces.IPosition) (interfaces.RelatableIterator, error) { tbx2, err := newShort(tbx) if err != nil { return nil, err } if region == nil { var l string var err error buf := bufio.NewReader(tbx2.bgzf) l, err = buf.ReadString('\n') for i := 0; i < int(tbx2.Index.Skip) || rune(l[0]) == tbx2.Index.MetaChar; i++ { l, err = buf.ReadString('\n') if err != nil { return nil, err } } if tbx2.Index.Skip == 0 && rune(l[0]) != tbx2.Index.MetaChar { buf = bufio.NewReader(io.MultiReader(strings.NewReader(l), buf)) } return bixerator{nil, buf, tbx2, region}, nil } cr, err := tbx2.ChunkedReader(region.Chrom(), int(region.Start()), int(region.End())) if err != nil { if cr != nil { tbx2.Close() cr.Close() } return nil, err } return bixerator{cr, bufio.NewReader(cr), tbx2, region}, nil }
func main() { // 1. Listen for connections. if ln, err := net.Listen("tcp", ":8080"); err == nil { for { // 2. Accept connections. if conn, err := ln.Accept(); err == nil { reader := bufio.NewReader(conn) // 3. Read requests from the client. if req, err := http.ReadRequest(reader); err == nil { // 4. Connect to the backend web server. if be, err := net.Dial("tcp", "127.0.0.1:8081"); err == nil { be_reader := bufio.NewReader(be) // 5. Send the request to the backend. if err := req.Write(be); err == nil { // 6. Read the response from the backend. if resp, err := http.ReadResponse(be_reader, req); err == nil { // 7. Send the response to the client, making sure to close it. resp.Close = true if err := resp.Write(conn); err == nil { log.Printf("proxied %s: got %d", req.URL.Path, resp.StatusCode) } conn.Close() // Repeat back at 2: accept the next connection. } } } } } } } }
// handleConnection is spawned once per connection from a client, // and exits when the client is done sending requests func handleConnection(conn net.Conn) { // always close the conn no matter how this function exits: defer conn.Close() reader := bufio.NewReader(conn) // loop to handle multiple requests from user conn, // since we are now running concurrently: for { req, err := http.ReadRequest(reader) if err != nil { if err != io.EOF { log.Printf("Failed to read request: %s", err) } return } // connect to a backend and send the request along if be, err := net.Dial("tcp", "127.0.0.1:8081"); err == nil { be_reader := bufio.NewReader(be) if err := req.Write(be); err == nil { if resp, err := http.ReadResponse(be_reader, req); err == nil { FixHttp10Response(resp, req) if err := resp.Write(conn); err == nil { log.Printf("proxied %s: got %d", req.URL.Path, resp.StatusCode) } if resp.Close { return } } } } } }
func TestGenerate(t *testing.T) { const testTemplate = ` html: body: br awef wef "fwef'wef" 22323 0.1112 49U true false nil inf -inf ; ;` p := otp.ConnectTo(ots.ConnectTo(bufio.NewReader(bytes.NewBufferString(testTemplate)))) if tpl, err := p.Template(); err == nil { m := conv.Map(tpl) conv.Resolve(m) buf := bytes.NewBuffer(nil) otg.ConnectTo(buf).Write(m) s := buf.String() t.Log(s) p0 := otp.ConnectTo(ots.ConnectTo(bufio.NewReader(bytes.NewBufferString(s)))) if tpl0, err0 := p0.Template(); err0 == nil { m0 := conv.Map(tpl0) conv.Resolve(m0) prettyPrintObject(m0, t) } } else { t.Fatal(err) } { buf := bytes.NewBuffer(nil) otg.ConnectTo(buf).Write(conv.Begin(otm.Qualident{Class: "test"}).Value("asdf asdf asdf `asdfasdf").Value([]uint8{0, 1, 2, 3, 4}).End()) s := buf.String() t.Log(s) } }
func main() { conn, err := net.Dial("tcp", "127.0.0.1:8081") if err != nil { fmt.Println("connect to server error!") return } defer conn.Close() message, _ := bufio.NewReader(conn).ReadString('\n') fmt.Print(message) for { // read in input from stdin reader := bufio.NewReader(os.Stdin) fmt.Print("Text to send: ") text, _ := reader.ReadString('\n') // send to socket _, _ = conn.Write([]byte(text)) //fmt.Fprintf(conn, text + "\n") // listen for reply message, _ := bufio.NewReader(conn).ReadString('\n') if (message == "Good bye\n") { break } else { fmt.Print("Message from server: " + message) } } fmt.Println("conn is closed") }
func check(dest, src string) { f, err := os.Open(src) if err != nil { fmt.Printf("couldn't open %q: %v\n", src, err) return } defer f.Close() freader := bufio.NewReader(f) g, err := os.Open(dest) if err != nil { fmt.Printf("couldn't open %q: %v\n", src, err) return } defer g.Close() greader := bufio.NewReader(g) for { fb, ferr := freader.ReadByte() gb, gerr := greader.ReadByte() if ferr == io.EOF && gerr == io.EOF { break } if fb == gb { continue } fmt.Println("FAIL") return } fmt.Println("PASS") }
func prolixSpawn(args []string) { if verbose { fmt.Printf("Running: %q\n", args) } cmd := exec.Command(args[0], args[1:]...) outReader, err := cmd.StdoutPipe() if err != nil { panic(err) } outc := make(chan string) errReader, err := cmd.StderrPipe() if err != nil { panic(err) } errc := make(chan string) err = cmd.Start() if err != nil { panic(err) } go readPipe(bufio.NewReader(outReader), outc) go readPipe(bufio.NewReader(errReader), errc) doneDemux := make(chan string) go demux(outc, errc, doneDemux) res := <-doneDemux if res == "kill" { shutdown(cmd.Process) } err = cmd.Wait() // TODO(gaal): exit with child err? }
func Tail(conn *irc.Conn, channel, filename string, fn func(string) bool) { AutoJoin(conn, channel) f, err := os.Open(filename, 0, 0) if err != nil { log.Println(err) return } _, err = f.Seek(0, 2) if err != nil { log.Println(err) return } b := bufio.NewReader(f) go func() { for { l, err := b.ReadBytes('\n') if err != nil { if err == os.EOF { time.Sleep(1e9) b = bufio.NewReader(f) continue } log.Println(err) break } s := string(l[:len(l)-1]) if fn(s) { conn.Privmsg(channel, s) } } }() }
func main() { flag.Parse() if *showVersion { fmt.Printf("json2csv v1.1\n") return } var reader *bufio.Reader var writer *csv.Writer if *inputFile != "" { file, err := os.OpenFile(*inputFile, os.O_RDONLY, 0600) if err != nil { log.Printf("Error %s opening %v", err, *inputFile) return } reader = bufio.NewReader(file) } else { reader = bufio.NewReader(os.Stdin) } if *outputFile != "" { file, err := os.OpenFile(*outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Printf("Error %s opening outputFile %v", err, *outputFile) } writer = csv.NewWriter(file) } else { writer = csv.NewWriter(os.Stdout) } json2csv(reader, writer, keys) }
// handleConnection is spawned once per connection from a client, and exits when the client is // done sending requests. func handleConnection(conn net.Conn) { defer conn.Close() reader := bufio.NewReader(conn) for { req, err := http.ReadRequest(reader) if err != nil { if err != io.EOF { log.Printf("Failed to read request: %s", err) } return } // Connect to a backend and send the request along. if be, err := net.Dial("tcp", "127.0.0.1:8081"); err == nil { be_reader := bufio.NewReader(be) if err := req.Write(be); err == nil { if resp, err := http.ReadResponse(be_reader, req); err == nil { FixHttp10Response(resp, req) if err := resp.Write(conn); err == nil { log.Printf("proxied %s: got %d", req.URL.Path, resp.StatusCode) } if resp.Close { return } } } } } }
/* * This function is test server capabilties to handle load and concurrency */ func TestServerConcurrently(t *testing.T) { done := make(chan bool, 10) clientContents := []struct{ content string }{{"ONE"}, {"TWO"}, {"THREE"}, {"FOUR"}, {"FIVE"}, {"SIX"}, {"SEVEN"}, {"EIGHT"}, {"NINE"}, {"TEN"}} filename := "f" i := 1 //it does not check for concurrency but test server ability to buffer and handle many clients at once for _, e := range clientContents { con := getConnection(t) defer con.Close() reader := bufio.NewReader(con) go routineWork(t, con, reader, done, filename+strconv.Itoa(i), e.content) i++ } //do concurrency test for _, e := range clientContents { con := getConnection(t) defer con.Close() reader := bufio.NewReader(con) go concurrent(t, con, reader, done, filename+strconv.Itoa(i), e.content) i++ } // Wait for tests to finish for i := 1; i <= 2*len(clientContents); i++ { <-done } }
func main() { var filename string var in *bufio.Reader var err error // use the file if there is an argument, otherwise use stdin if flag.NArg() == 0 { filename = "stdin" in = bufio.NewReader(os.NewFile(0, "stdin")) } else { filename = flag.Arg(0) f, err := os.Open(filename) if err != nil { log.Fatal("Open:", err) } defer f.Close() if fi, err := f.Stat(); err != nil || fi.IsDir() { log.Fatalf("err(%s) or %s IsDir", err, filename) } in = bufio.NewReader(f) } goSource, err := transliterate(filename, in) if err != nil { log.Fatalf("%s", err) } err = compileAndLink(goSource, outPath) if err != nil { log.Fatalf("compileAndLink('%s')", goSource, err) } }
func getLogReader(logfile string, logf *os.File) (*bufio.Reader, error) { var rdr *bufio.Reader // Is this a gzip file? if path.Ext(logfile) == gzipext { gzrdr, err := gzip.NewReader(logf) if err != nil { return nil, err } rdr = bufio.NewReader(gzrdr) } else { // See if the file has shrunk. If so, read from the beginning. fi, err := logf.Stat() if err != nil { return nil, err } if fi.Size() < pos { pos = 0 } logf.Seek(pos, os.SEEK_SET) fmt.Printf("Starting read at offset %d\n", pos) rdr = bufio.NewReader(logf) } return rdr, nil }
func (s *Stream) consume(resp *http.Response) { reader := bufio.NewReader(resp.Body) var ( b []byte err error ) for { select { case <-s.stop: resp.Body.Close() close(s.stop) close(s.errors) close(s.data) return default: b, err = s.consumer.Consume(reader) if err != nil { resp.Body.Close() time.Sleep(10 * time.Second) if resp, err = s.connect(); err != nil { s.errors <- err continue } reader = bufio.NewReader(resp.Body) } s.data <- b } } }