本文整理汇总了Golang中bufio.NewReader函数的典型用法代码示例。如果您正苦于以下问题:Golang NewReader函数的具体用法?Golang NewReader怎么用?Golang NewReader使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewReader函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Symbol
// 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
}
}
}
示例2: main
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)
}
}
示例3: dsInTxt
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)
}
}
}
示例4: waiter
// 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)
}
示例5: TestStarRequest
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)
}
}
示例6: TestHandling
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()
}
示例7: Dial
// 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
}
示例8: TestServeHTTPReadRequestError
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)
}
}
示例9: Start
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)
}
}
示例10: ProcessApiBlueprintTest
/**
* 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
}
示例11: main
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)
}
示例12: handleConn
// 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)
}
示例13: ReadBinlog
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
}
示例14: test
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()
}
示例15: bodyDiff
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
}
}
}