本文整理匯總了Golang中io.Writer函數的典型用法代碼示例。如果您正苦於以下問題:Golang Writer函數的具體用法?Golang Writer怎麽用?Golang Writer使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Writer函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Accept
// Accept starts a new SMTP session using io.ReadWriteCloser
func Accept(remoteAddress string, conn io.ReadWriteCloser, storage storage.Storage, messageChan chan *data.Message, hostname string, monkey monkey.ChaosMonkey) {
defer conn.Close()
proto := smtp.NewProtocol()
proto.Hostname = hostname
var link *linkio.Link
reader := io.Reader(conn)
writer := io.Writer(conn)
if monkey != nil {
linkSpeed := monkey.LinkSpeed()
if linkSpeed != nil {
link = linkio.NewLink(*linkSpeed * linkio.BytePerSecond)
reader = link.NewLinkReader(io.Reader(conn))
writer = link.NewLinkWriter(io.Writer(conn))
}
}
session := &Session{conn, proto, storage, messageChan, remoteAddress, false, "", link, reader, writer, monkey}
proto.LogHandler = session.logf
proto.MessageReceivedHandler = session.acceptMessage
proto.ValidateSenderHandler = session.validateSender
proto.ValidateRecipientHandler = session.validateRecipient
proto.ValidateAuthenticationHandler = session.validateAuthentication
proto.GetAuthenticationMechanismsHandler = func() []string { return []string{"PLAIN"} }
session.logf("Starting session")
session.Write(proto.Start())
for session.Read() == true {
if monkey != nil && monkey.Disconnect != nil && monkey.Disconnect() {
session.conn.Close()
break
}
}
session.logf("Session ended")
}
示例2: TestWriteReadReplication
func TestWriteReadReplication(t *testing.T) {
SetupCluster()
log.Info("Testing TestWriteReadReplication...")
_, other := GetProcessForPath("/tests/replication/write/read")
resolv := tc.nodes[0].Cluster.Rings.GetGlobalRing().Resolve("/tests/replication/write/read")
buf := buffer.NewFromString("write1")
err := other.Fss.Write(fs.NewPath("/tests/replication/write/read"), buf.Size, "application/mytest", buf, nil)
if err != nil {
t.Errorf("1) Got an error while write: %s", err)
}
// test force local on exists
context := tc.nodes[0].Fss.NewContext()
context.ForceLocal = true
bufwriter := bytes.NewBuffer(make([]byte, 0))
buffer := io.Writer(bufwriter)
n, err := other.Fss.Read(fs.NewPath("/tests/replication/write/read"), 0, -1, 0, buffer, context)
if err != fs.ErrorFileNotFound {
t.Errorf("2) File shouldn't exists on another node: %s", err)
}
// force local replication on each secondary
tc.nodes[resolv.GetOnline(1).Id].Fss.Flush()
tc.nodes[resolv.GetOnline(2).Id].Fss.Flush()
// check on first secondary
secondaryid := resolv.GetOnline(1).Id
context = tc.nodes[secondaryid].Fss.NewContext()
context.ForceLocal = true
bufwriter = bytes.NewBuffer(make([]byte, 0))
buffer = io.Writer(bufwriter)
n, err = tc.nodes[secondaryid].Fss.Read(fs.NewPath("/tests/replication/write/read"), 0, -1, 0, buffer, context)
if err != nil {
t.Errorf("3) Got an error from read: %s", err)
}
if n != buf.Size || bytes.Compare(bufwriter.Bytes(), buf.Bytes()) != 0 {
t.Errorf("4) Didn't read what was written: %s!=%s", buf.Bytes(), bufwriter)
}
// check on second secondary
secondaryid = resolv.GetOnline(2).Id
context = tc.nodes[secondaryid].Fss.NewContext()
context.ForceLocal = true
bufwriter = bytes.NewBuffer(make([]byte, 0))
buffer = io.Writer(bufwriter)
n, err = tc.nodes[secondaryid].Fss.Read(fs.NewPath("/tests/replication/write/read"), 0, -1, 0, buffer, context)
if err != nil {
t.Errorf("3) Got an error from read: %s", err)
}
if n != buf.Size || bytes.Compare(bufwriter.Bytes(), buf.Bytes()) != 0 {
t.Errorf("4) Didn't read what was written: %s!=%s", buf.Bytes(), bufwriter)
}
}
示例3: SimpleWOFLogger
func SimpleWOFLogger(prefix string) *WOFLogger {
logger := NewWOFLogger(prefix)
stdout := io.Writer(os.Stdout)
stderr := io.Writer(os.Stderr)
logger.AddLogger(stdout, "status")
logger.AddLogger(stderr, "error")
return logger
}
示例4: EnvmanJSONPrint
// EnvmanJSONPrint ...
func EnvmanJSONPrint(envstorePth string) (string, error) {
logLevel := log.GetLevel().String()
args := []string{"--loglevel", logLevel, "--path", envstorePth, "print", "--format", "json", "--expand"}
var outBuffer bytes.Buffer
var errBuffer bytes.Buffer
if err := cmdex.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "envman", args...); err != nil {
return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
}
return outBuffer.String(), nil
}
示例5: StepmanJSONLocalStepInfo
// StepmanJSONLocalStepInfo ...
func StepmanJSONLocalStepInfo(pth string) (string, error) {
logLevel := log.GetLevel().String()
args := []string{"--debug", "--loglevel", logLevel, "step-info", "--step-yml", pth, "--format", "json"}
var outBuffer bytes.Buffer
var errBuffer bytes.Buffer
if err := cmdex.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "stepman", args...); err != nil {
return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
}
return outBuffer.String(), nil
}
示例6: InitWriter
func (e *Encrypter) InitWriter(fileWriter io.Writer) (io.Writer, error) {
if e.streamWriter != nil {
return io.Writer(e), fmt.Errorf("Encrypt writer already inited")
}
encStream, iv, err := getEncryptStream(e.passphrase)
if err != nil {
return io.Writer(e), err
}
if _, err := fileWriter.Write(iv); err != nil {
return io.Writer(e), err
}
e.streamWriter = &cipher.StreamWriter{S: encStream, W: fileWriter}
return io.Writer(e), nil
}
示例7: StepmanJSONStepLibStepInfo
// StepmanJSONStepLibStepInfo ...
func StepmanJSONStepLibStepInfo(collection, stepID, stepVersion string) (string, error) {
logLevel := log.GetLevel().String()
args := []string{"--debug", "--loglevel", logLevel, "step-info", "--collection", collection,
"--id", stepID, "--version", stepVersion, "--format", "json"}
var outBuffer bytes.Buffer
var errBuffer bytes.Buffer
if err := cmdex.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "stepman", args...); err != nil {
return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
}
return outBuffer.String(), nil
}
示例8: writeIndex
func writeIndex(outPath string) {
outFile, err := os.Create(outPath)
defer outFile.Close()
if err != nil {
panic(err)
}
writer := bufio.NewWriterSize(io.Writer(outFile), writerBufSize)
var v *list.List
dBuf := make([]byte, 4)
tfBuf := make([]byte, 4)
pBuf := make([]byte, 4)
for _, k := range dictionary.keys {
v = dictionary.m[k]
writer.WriteString(k + ",")
var posting *Posting
for el := v.Front(); el != nil; el = el.Next() {
posting = el.Value.(*Posting)
binary.PutUvarint(dBuf, uint64(posting.doc))
writer.Write(dBuf)
dBuf = []byte{0, 0, 0, 0}
binary.PutUvarint(tfBuf, uint64(posting.tf))
writer.Write(tfBuf)
tfBuf = []byte{0, 0, 0, 0}
for posEl := posting.pos.Front(); posEl != nil; posEl = posEl.Next() {
pos := posEl.Value.(uint32)
binary.PutUvarint(pBuf, uint64(pos))
writer.Write(pBuf)
pBuf = []byte{0, 0, 0, 0}
}
}
writer.Write([]byte{0, 0, 0, 0})
}
writer.Flush()
}
示例9: ContainerLogs
// ContainerLogs hooks up a container's stdout and stderr streams
// configured with the given struct.
func (c *Container) ContainerLogs(name string, config *backend.ContainerLogsConfig, started chan struct{}) error {
defer trace.End(trace.Begin(""))
// Look up the container name in the metadata cache to get long ID
vc := cache.ContainerCache().GetContainer(name)
if vc == nil {
return NotFoundError(name)
}
name = vc.ContainerID
tailLines, since, err := c.validateContainerLogsConfig(vc, config)
if err != nil {
return err
}
// Outstream modification (from Docker's code) so the stream is streamed with the
// necessary headers that the CLI expects. This is Docker's scheme.
wf := ioutils.NewWriteFlusher(config.OutStream)
defer wf.Close()
wf.Flush()
outStream := io.Writer(wf)
if !vc.Config.Tty {
outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
}
// Make a call to our proxy to handle the remoting
err = c.containerProxy.StreamContainerLogs(name, outStream, started, config.Timestamps, config.Follow, since, tailLines)
return err
}
示例10: CreateBufferedWriter
// CreateBufferedWriter ...
func CreateBufferedWriter(buff *bytes.Buffer, writers ...io.Writer) io.Writer {
if len(writers) > 0 {
allWriters := append([]io.Writer{buff}, writers...)
return io.MultiWriter(allWriters...)
}
return io.Writer(buff)
}
示例11: TestCx2Sif
//
// Read a CX file and generate SIF.
//
func TestCx2Sif(t *testing.T) {
output := new(bytes.Buffer)
w := io.Writer(output)
file, err := os.Open("../test_data/galcxStyle2.json")
if err != nil {
t.Fatal("Error:", err)
return
}
// Close input file at the end of this
defer file.Close()
c2s := converter.Cx2Sif{}
c2s.Convert(bufio.NewReader(file), w)
result := output.String()
lines := strings.Split(result, "\n")
for idx := range lines {
if lines[idx] == "" {
fmt.Println(idx, ": EMPTY")
} else {
fmt.Println(idx, ": ", lines[idx])
}
}
if len(lines) != 363 {
t.Errorf("Expected 363, got %d", len(lines))
}
}
示例12: Open
func Open(path string) (*Graph, error) {
var log *io.ReadWriter
if path != "" {
l, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
var rw io.ReadWriter = l
log = &rw
}
g := &Graph{}
g.indexes = makeIndexSet()
if log != nil {
w := io.Writer(*log)
g.log = &w
r := api.NodeReader{}
n := &Node{}
for {
node, err := r.Read(*log)
if err == io.EOF {
break
} else if err != nil {
panic(err)
}
n.FromApi(node)
g.indexes.add(*n)
}
}
return g, nil
}
示例13: testSif2Cx
func testSif2Cx(fName string, t *testing.T) {
output := new(bytes.Buffer)
w := io.Writer(output)
f, err := os.Open(fName)
if err != nil {
t.Fatal("Error:", err)
return
}
// Close input file at the end of this
defer f.Close()
s2c := Sif2Cx{Delimiter: rune(' ')}
s2c.Convert(bufio.NewReader(f), w)
result := output.String()
t.Log(result)
t.Log("Output length = ", len(result))
dec := json.NewDecoder(strings.NewReader(result))
var cx []interface{}
dec.Decode(&cx)
t.Log(cx)
}
示例14: StorePost
func StorePost(w http.ResponseWriter, req *http.Request) {
filename := uuid.NewV4().String()
now := time.Now().Format("20060102")
path := repo + "/" + now
err := os.MkdirAll(path, 0755)
if err == nil {
fullpath := path + "/" + filename
f, err := os.Create(fullpath)
if err == nil {
defer f.Close()
_, err := io.Copy(io.Writer(f), req.Body)
if err == nil {
log.Printf("%+v", req)
requestUri := "http://" + req.Host + req.RequestURI + now + "/" + filename
w.Write([]byte("Store OK : " + requestUri))
} else {
ServerError(w, req, err)
}
} else {
ServerError(w, req, err)
}
} else {
ServerError(w, req, err)
}
}
示例15: WriteLock
// WriteLock writes the lock as YAML.
//
// Params:
// - lockfile: A *cfg.Lockfile to render.
// - out (io.Writer): An output stream to write to. Default is os.Stdout.
func WriteLock(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
skip := p.Get("skip", false).(bool)
if skip {
return false, nil
}
lockfile := p.Get("lockfile", nil).(*cfg.Lockfile)
Info("Writing glide.lock file")
data, err := lockfile.Marshal()
if err != nil {
return nil, err
}
var out io.Writer
file, err := os.Create("glide.lock")
if err != nil {
return false, err
}
defer file.Close()
out = io.Writer(file)
out.Write(data)
return true, nil
}