当前位置: 首页>>代码示例>>Golang>>正文


Golang bufio.Writer类代码示例

本文整理汇总了Golang中bufio.Writer的典型用法代码示例。如果您正苦于以下问题:Golang Writer类的具体用法?Golang Writer怎么用?Golang Writer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Writer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: writeSuccessResponseHeader

func writeSuccessResponseHeader(w *bufio.Writer, opcode uint8, keyLength, extraLength,
	totalBodyLength int, opaque uint32, flush bool) error {

	header := resHeadPool.Get().(ResponseHeader)

	header.Magic = MagicResponse
	header.Opcode = opcode
	header.KeyLength = uint16(keyLength)
	header.ExtraLength = uint8(extraLength)
	header.DataType = uint8(0)
	header.Status = StatusSuccess
	header.TotalBodyLength = uint32(totalBodyLength)
	header.OpaqueToken = opaque
	header.CASToken = uint64(0)

	if err := writeResponseHeader(w, header); err != nil {
		resHeadPool.Put(header)
		return err
	}

	if flush {
		if err := w.Flush(); err != nil {
			resHeadPool.Put(header)
			return err
		}
	}

	metrics.IncCounterBy(common.MetricBytesWrittenRemote, resHeaderLen)
	resHeadPool.Put(header)

	return nil
}
开发者ID:Netflix,项目名称:rend,代码行数:32,代码来源:respond.go

示例2: writeBodyFixedSize

func writeBodyFixedSize(w *bufio.Writer, r io.Reader, size int64) error {
	if size > maxSmallFileSize {
		// w buffer must be empty for triggering
		// sendfile path in bufio.Writer.ReadFrom.
		if err := w.Flush(); err != nil {
			return err
		}
	}

	// Unwrap a single limited reader for triggering sendfile path
	// in net.TCPConn.ReadFrom.
	lr, ok := r.(*io.LimitedReader)
	if ok {
		r = lr.R
	}

	n, err := copyZeroAlloc(w, r)

	if ok {
		lr.N -= n
	}

	if n != size && err == nil {
		err = fmt.Errorf("copied %d bytes from body stream instead of %d bytes", n, size)
	}
	return err
}
开发者ID:stellar,项目名称:bridge-server,代码行数:27,代码来源:http.go

示例3: outputResults

func (r Resolver) outputResults(w *bufio.Writer, results gresults) {
	var zip, city, state, stateName, county, country, countryName string
	var latitude, longitude float32

	var comp addressComponent
	var err error
	for _, res := range results.Results {
		if comp, err = res.findAddressComponent(zipType); err == nil {
			zip = comp.LongName
		}
		if comp, err = res.findAddressComponent(cityType); err == nil {
			city = comp.LongName
		}
		if comp, err = res.findAddressComponent(countyType); err == nil {
			county = comp.LongName
		}
		if comp, err = res.findAddressComponent(stateType); err == nil {
			state = strings.ToUpper(comp.ShortName)
			stateName = comp.LongName
		}
		if comp, err = res.findAddressComponent(countryType); err == nil {
			country = strings.ToUpper(comp.ShortName)
			countryName = comp.LongName
		}
		latitude = res.Geometry.Location.Lat
		longitude = res.Geometry.Location.Lng
	}
	w.WriteString(fmt.Sprintf("%v,\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",%v,%v\n", country, zip, city, state, stateName, county, countryName, latitude, longitude))
	w.Flush()
}
开发者ID:rchargel,项目名称:zilch,代码行数:30,代码来源:resolver.go

示例4: NewStreamReader

// NewStreamReader returns a reader, which replays all the data generated by sw.
//
// The returned reader may be passed to Response.SetBodyStream.
//
// Close must be called on the returned reader after all the required data
// has been read. Otherwise goroutine leak may occur.
//
// See also Response.SetBodyStreamWriter.
func NewStreamReader(sw StreamWriter) io.ReadCloser {
	pc := fasthttputil.NewPipeConns()
	pw := pc.Conn1()
	pr := pc.Conn2()

	var bw *bufio.Writer
	v := streamWriterBufPool.Get()
	if v == nil {
		bw = bufio.NewWriter(pw)
	} else {
		bw = v.(*bufio.Writer)
		bw.Reset(pw)
	}

	go func() {
		defer func() {
			if r := recover(); r != nil {
				defaultLogger.Printf("panic in StreamWriter: %s\nStack trace:\n%s", r, debug.Stack())
			}
		}()

		sw(bw)
		bw.Flush()
		pw.Close()

		streamWriterBufPool.Put(bw)
	}()

	return pr
}
开发者ID:cloudfoundry-incubator,项目名称:routing-perf-release,代码行数:38,代码来源:stream.go

示例5: authenticate

// authenticate authenticates ourselves with the X server.
// displayStr is the "12" out of ":12.0".
func authenticate(w *bufio.Writer, displayStr string) os.Error {
	key, value, err := readAuth(displayStr)
	if err != nil {
		return err
	}
	// Assume that the authentication protocol is "MIT-MAGIC-COOKIE-1".
	if len(key) != 18 || len(value) != 16 {
		return os.NewError("unsupported Xauth")
	}
	// 0x006c means little-endian. 0x000b, 0x0000 means X major version 11, minor version 0.
	// 0x0012 and 0x0010 means the auth key and value have lengths 18 and 16.
	// The final 0x0000 is padding, so that the string length is a multiple of 4.
	_, err = io.WriteString(w, "\x6c\x00\x0b\x00\x00\x00\x12\x00\x10\x00\x00\x00")
	if err != nil {
		return err
	}
	_, err = io.WriteString(w, key)
	if err != nil {
		return err
	}
	// Again, the 0x0000 is padding.
	_, err = io.WriteString(w, "\x00\x00")
	if err != nil {
		return err
	}
	_, err = io.WriteString(w, value)
	if err != nil {
		return err
	}
	err = w.Flush()
	if err != nil {
		return err
	}
	return nil
}
开发者ID:machinaut,项目名称:go,代码行数:37,代码来源:conn.go

示例6: WriteResponse

func (c *DefaultServerCodec) WriteResponse(wr *bufio.Writer, proto *Proto) (err error) {
	log.Debug("write proto: %v", proto)
	// packlen =header(16) + body
	if err = binary.Write(wr, binary.BigEndian, uint32(rawHeaderLen)+uint32(len(proto.Body))); err != nil {
		log.Error("packLen: binary.Write() error(%v)", err)
		return
	}
	if err = binary.Write(wr, binary.BigEndian, rawHeaderLen); err != nil {
		log.Error("headerLen: binary.Write() error(%v)", err)
		return
	}
	if err = binary.Write(wr, binary.BigEndian, proto.Ver); err != nil {
		log.Error("protoVer: binary.Write() error(%v)", err)
		return
	}
	if err = binary.Write(wr, binary.BigEndian, proto.Operation); err != nil {
		log.Error("operation: binary.Write() error(%v)", err)
		return
	}
	if err = binary.Write(wr, binary.BigEndian, proto.SeqId); err != nil {
		log.Error("seqId: binary.Write() error(%v)", err)
		return
	}
	if proto.Body != nil {
		if _, err = wr.Write(proto.Body); err != nil {
			log.Error("body: wr.Write() error(%v)", err)
			return
		}
	}
	return wr.Flush()
}
开发者ID:xingskycn,项目名称:goim,代码行数:31,代码来源:codec.go

示例7: Write

// Write writes response to w.
//
// Write doesn't flush response to w for performance reasons.
func (resp *Response) Write(w *bufio.Writer) error {
	var err error
	if resp.bodyStream != nil {
		contentLength := resp.Header.ContentLength()
		if contentLength >= 0 {
			if err = resp.Header.Write(w); err != nil {
				return err
			}
			if err = writeBodyFixedSize(w, resp.bodyStream, contentLength); err != nil {
				return err
			}
		} else {
			resp.Header.SetContentLength(-1)
			if err = resp.Header.Write(w); err != nil {
				return err
			}
			if err = writeBodyChunked(w, resp.bodyStream); err != nil {
				return err
			}
		}
		if bsc, ok := resp.bodyStream.(io.Closer); ok {
			err = bsc.Close()
		}
		return err
	}

	resp.Header.SetContentLength(len(resp.body))
	if err = resp.Header.Write(w); err != nil {
		return err
	}
	_, err = w.Write(resp.body)
	return err
}
开发者ID:mgostick,项目名称:fasthttp,代码行数:36,代码来源:http.go

示例8: doWriteRune

func doWriteRune(w *bufio.Writer) {
	if written, err := w.WriteRune(rune('o')); err != nil {
		log.Fatalf("failed writing a rune: %s", err)
	} else {
		log.Printf("Wrote rune in %d bytes", written)
	}
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:7,代码来源:writing.go

示例9: doWriteString

func doWriteString(w *bufio.Writer) {
	if written, err := w.WriteString(", The Standard Library\n"); err != nil {
		log.Fatalf("failed writing string: %s", err)
	} else {
		log.Printf("Wrote string in %d bytes", written)
	}
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:7,代码来源:writing.go

示例10: emit_allele_path_item

func emit_allele_path_item(ofp *bufio.Writer) {

	for k := range g_allele_path_item {

		for i := 0; i < len(g_allele_path_item[k]); i++ {
			s := fmt.Sprintf("%d,%d,%d,%d,%d,%s\n",
				g_allele_path_item[k][i].AlleleId,
				g_allele_path_item[k][i].PathItemIndex,
				g_allele_path_item[k][i].SequenceId,
				g_allele_path_item[k][i].Start,
				g_allele_path_item[k][i].Length,
				g_allele_path_item[k][i].StrandIsForward)
			ofp.Write([]byte(s))
		}
	}

	return

	for allele_name := range g_allele_sequenceid_path {

		allele_id := g_allele_name_id_map[allele_name]

		for i := 0; i < len(g_allele_sequenceid_path[allele_name]); i++ {
			seqid := g_allele_sequenceid_path[allele_name][i]
			s := fmt.Sprintf("%d,%d,%d,%s,%s,%s\n", allele_id, i, seqid, "NULL", "NULL", "'TRUE'")
			ofp.Write([]byte(s))
		}

	}
}
开发者ID:sguthrie,项目名称:hgvm-lighting-graph,代码行数:30,代码来源:fj2allele.go

示例11: Write

// Write writes request to w.
//
// Write doesn't flush request to w for performance reasons.
func (req *Request) Write(w *bufio.Writer) error {
	if len(req.Header.Host()) == 0 {
		uri := req.URI()
		host := uri.Host()
		if len(host) == 0 {
			return errRequestHostRequired
		}
		req.Header.SetHostBytes(host)
		req.Header.SetRequestURIBytes(uri.RequestURI())
	}

	body := req.body
	var err error
	if req.multipartForm != nil && len(req.body) == 0 {
		body, err = marshalMultipartForm(req.multipartForm, req.multipartFormBoundary)
		if err != nil {
			return fmt.Errorf("error when marshaling multipart form: %s", err)
		}
		req.Header.SetMultipartFormBoundary(req.multipartFormBoundary)
	}

	hasBody := !req.Header.noBody()
	if hasBody {
		req.Header.SetContentLength(len(body))
	}
	if err = req.Header.Write(w); err != nil {
		return err
	}
	if hasBody {
		_, err = w.Write(body)
	} else if len(body) > 0 {
		return fmt.Errorf("Non-zero body for non-POST request. body=%q", body)
	}
	return err
}
开发者ID:anilprasad,项目名称:fasthttp,代码行数:38,代码来源:http.go

示例12: writeln

func writeln(w *bufio.Writer, s string) error {
	_, err := w.WriteString(s)
	if err != nil {
		return err
	}
	return newLine(w)
}
开发者ID:ziutek,项目名称:gogammu,代码行数:7,代码来源:sms.go

示例13: Write

// Function IHex.Write writes the representation of the file to the writer `wr`.
func (ix *IHex) Write(wr *bufio.Writer) (err error) {
	for start, data := range ix.areas {
		i := 0

		for i < len(data) {
			var chunk []byte

			if i+16 <= len(data) {
				chunk = data[i : i+16]
			} else {
				chunk = data[i:]
			}

			_, err := wr.Write([]byte(makeLine(0x00, start, chunk)))
			if err != nil {
				return err
			}

			start += 16
		}
	}

	_, err = wr.Write([]byte(makeLine(0x01, 0, []byte{})))
	if err != nil {
		return err
	}

	return nil
}
开发者ID:iand,项目名称:go,代码行数:30,代码来源:ihex.go

示例14: writeErrorResponseHeader

func writeErrorResponseHeader(w *bufio.Writer, opcode uint8, status uint16, opaque uint32) error {
	header := resHeadPool.Get().(ResponseHeader)

	header.Magic = MagicResponse
	header.Opcode = opcode
	header.KeyLength = uint16(0)
	header.ExtraLength = uint8(0)
	header.DataType = uint8(0)
	header.Status = status
	header.TotalBodyLength = uint32(0)
	header.OpaqueToken = opaque
	header.CASToken = uint64(0)

	if err := writeResponseHeader(w, header); err != nil {
		resHeadPool.Put(header)
		return err
	}

	if err := w.Flush(); err != nil {
		resHeadPool.Put(header)
		return err
	}

	metrics.IncCounterBy(common.MetricBytesWrittenRemote, resHeaderLen)
	resHeadPool.Put(header)

	return nil
}
开发者ID:Netflix,项目名称:rend,代码行数:28,代码来源:respond.go

示例15: sendUpdates

func (t *TcpPlayer) sendUpdates(w *bufio.Writer, wg *sync.WaitGroup) {
	defer wg.Done()

	enc := json.NewEncoder(w)

	lastTurnSent := -1
	for update := range t.update {
		t.stateL.Lock()
		t.state = update
		t.stateL.Unlock()

		if update.Turn == lastTurnSent {
			continue
		}

		if err := enc.Encode(update); err != nil {
			t.l.Errorf("[TCP] sending update to player, %v", err)
			return
		}

		if _, err := w.WriteRune('\n'); err != nil {
			t.l.Errorf("[TCP] sending EOL to player, %v", err)
			return
		}

		if err := w.Flush(); err != nil {
			t.l.Errorf("[TCP] flushing update to player, %v", err)
			return
		}
		lastTurnSent = update.Turn
	}
}
开发者ID:uiri,项目名称:bombertcp,代码行数:32,代码来源:player.go


注:本文中的bufio.Writer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。