本文整理汇总了Golang中bytes.NewBufferString函数的典型用法代码示例。如果您正苦于以下问题:Golang NewBufferString函数的具体用法?Golang NewBufferString怎么用?Golang NewBufferString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewBufferString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: deprecated_init
// this init function is deprecated, but I'm keeping it
// around just in case it proves useful in the future.
func deprecated_init() {
// if piping from stdin we can just exit
// and use the default Stdin value
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
return
}
// check for params after the double dash
// in the command string
for i, argv := range os.Args {
if argv == "--" {
arg := os.Args[i+1]
buf := bytes.NewBufferString(arg)
Stdin = NewParamSet(buf)
return
}
}
// else use the first variable in the list
if len(os.Args) > 1 {
buf := bytes.NewBufferString(os.Args[1])
Stdin = NewParamSet(buf)
}
}
示例2: TestDifferentStrings
func TestDifferentStrings(t *testing.T) {
s1 := "one\ntwo\nthree\nfour\n"
s2 := "one\nTwo\nthree\nfore\n"
a, b := bytes.NewBufferString(s1), bytes.NewBufferString(s2)
diffs, err := text.Compare(a, b)
if err != nil {
t.Error(err)
}
if len(diffs) != 2 {
t.Errorf("Expected 2 diffs, got %d", len(diffs))
}
if len(diffs) > 0 {
ed := core.Diff{Expected: "two", Actual: "Two", Pos: []string{"2"}}
ad := diffs[0]
if !ad.Equals(ed) {
t.Errorf("Expected %s but got %s", ed, ad)
}
}
if len(diffs) > 1 {
ed := core.Diff{Expected: "four", Actual: "fore", Pos: []string{"4"}}
ad := diffs[1]
if !ad.Equals(ed) {
t.Errorf("Expected %s but got %s", ed, ad)
}
}
}
示例3: TestDelete
func TestDelete(t *testing.T) {
buf := bytes.NewBufferString("[general]\nfoo=bar\nfoo2=bar2\nfoo3=baz\n")
cfg := ini.Parse(buf)
cfg.Delete("general", "foo")
out := new(bytes.Buffer)
cfg.Write(out)
correct := "[general]\nfoo2=bar2\nfoo3=baz\n\n"
if s := out.String(); s != correct {
t.Errorf("Incorrect INI after delete:\n%s", s)
}
buf = bytes.NewBufferString("[general]\nfoo=bar\nfoo2=bar2\nfoo3=baz\n")
cfg = ini.Parse(buf)
cfg.Delete("general", "foo2")
out = new(bytes.Buffer)
cfg.Write(out)
correct = "[general]\nfoo=bar\nfoo3=baz\n\n"
if s := out.String(); s != correct {
t.Errorf("Incorrect INI after delete:\n%s", s)
}
buf = bytes.NewBufferString("[general]\nfoo=bar\nfoo2=bar2\nfoo3=baz\n")
cfg = ini.Parse(buf)
cfg.Delete("general", "foo3")
out = new(bytes.Buffer)
cfg.Write(out)
correct = "[general]\nfoo=bar\nfoo2=bar2\n\n"
if s := out.String(); s != correct {
t.Errorf("Incorrect INI after delete:\n%s", s)
}
}
示例4: TestAddPool
func (s *S) TestAddPool(c *check.C) {
b := bytes.NewBufferString("name=pool1")
req, err := http.NewRequest("POST", "/pools", b)
c.Assert(err, check.IsNil)
req.Header.Set("Authorization", "bearer "+s.token.GetValue())
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
defer provision.RemovePool("pool1")
m := RunServer(true)
m.ServeHTTP(rec, req)
c.Assert(rec.Code, check.Equals, http.StatusCreated)
c.Assert(err, check.IsNil)
pools, err := provision.ListPools(bson.M{"_id": "pool1"})
c.Assert(err, check.IsNil)
c.Assert(pools, check.HasLen, 1)
b = bytes.NewBufferString("name=pool2&public=true")
req, err = http.NewRequest("POST", "/pools", b)
c.Assert(err, check.IsNil)
req.Header.Set("Authorization", "bearer "+s.token.GetValue())
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec = httptest.NewRecorder()
defer provision.RemovePool("pool2")
m.ServeHTTP(rec, req)
c.Assert(rec.Code, check.Equals, http.StatusCreated)
pools, err = provision.ListPools(bson.M{"_id": "pool2"})
c.Assert(err, check.IsNil)
c.Assert(pools[0].Public, check.Equals, true)
}
示例5: TestSimpleString
func TestSimpleString(t *testing.T) {
var data string
msg := bytes.NewBufferString("+This is a simple string\r\n+This simple string\rfails\r\n")
err := Scan(msg, &data)
if err != nil {
t.Fatal(err)
}
t.Logf("%q", data)
err = Scan(msg, &data)
if err != ErrMalformedSimpleString {
t.Fatal("simple string containing \\r did not fail")
} else {
t.Logf("err=%v", err)
}
t.Logf("%q", data)
msg = bytes.NewBufferString("+This simple string fails because of a \n\r\n")
err = Scan(msg, &data)
if err != ErrMalformedSimpleString {
t.Fatal("simple string containing \\n did not fail")
} else {
t.Logf("err=%v", err)
}
t.Logf("%q", data)
}
示例6: singReqDep
func singReqDep(url, ryaml, dyaml string) (*dtos.SingularityRequestParent, error) {
h := &http.Client{}
ru := url + `/api/requests`
du := url + `/api/deploys`
rrz, err := h.Post(ru, `application/json`, bytes.NewBufferString(ryaml))
if err != nil {
return nil, err
}
logBody("POST /api/requests", rrz)
dqz, err := h.Post(du, `application/json`, bytes.NewBufferString(dyaml))
if err != nil {
return nil, err
}
logBody("POST /api/deploys", dqz)
rqz, err := h.Get(ru)
time.Sleep(3 * time.Second)
resBody := logBody("GET /api/requests", rqz)
var sr dtos.SingularityRequestParentList
sr.Populate(resBody)
return sr[0], nil
}
示例7: TestJSON
func TestJSON(t *testing.T) {
wantMap := map[string]interface{}{
"a": "aye",
"b": "bee",
"c": "see",
}
wantArray := []interface{}{"1", "2", "3"}
tests := [][2]interface{}{
{`{"a":"aye","b":"bee","c":"see"}`, wantMap},
{[]byte(`{"a":"aye","b":"bee","c":"see"}`), wantMap},
{bytes.NewBufferString(`{"a":"aye","b":"bee","c":"see"}`), wantMap},
{`["1", "2", "3"]`, wantArray},
{[]byte(`["1", "2", "3"]`), wantArray},
{bytes.NewBufferString(`["1", "2", "3"]`), wantArray},
}
for _, test := range tests {
if have, err := JSON(test[0]); err == nil {
want := test[1]
if !reflect.DeepEqual(have, want) {
t.Error("output invalid:")
t.Errorf(" have: %+v\n", have)
t.Errorf(" want: %+v\n", want)
}
} else {
t.Error(err)
}
}
}
示例8: compare
func compare(
original string,
modified string,
block_size uint,
) (results <-chan BlockMatchResult, err error) {
originalFileContent := bytes.NewBufferString(original)
generator := filechecksum.NewFileChecksumGenerator(block_size)
_, reference, _, err := indexbuilder.BuildChecksumIndex(
generator,
originalFileContent,
)
if err != nil {
return
}
modifiedContent := bytes.NewBufferString(modified)
results = (&Comparer{}).StartFindMatchingBlocks(
modifiedContent,
0,
generator,
reference,
)
return
}
示例9: runCommand
func (res digDnsResolver) runCommand(cmdName string, args ...string) (stdout, stderr string, err error) {
res.logger.Debug("Dig Dns Resolver", "Running command: %s %s", cmdName, strings.Join(args, " "))
cmd := exec.Command(cmdName, args...)
stdoutWriter := bytes.NewBufferString("")
stderrWriter := bytes.NewBufferString("")
cmd.Stdout = stdoutWriter
cmd.Stderr = stderrWriter
err = cmd.Start()
if err != nil {
err = bosherr.WrapError(err, "Starting dig command")
return
}
err = cmd.Wait()
stdout = string(stdoutWriter.Bytes())
stderr = string(stderrWriter.Bytes())
res.logger.Debug("Cmd Runner", "Stdout: %s", stdout)
res.logger.Debug("Cmd Runner", "Stderr: %s", stderr)
res.logger.Debug("Cmd Runner", "Successful: %t", err == nil)
if err != nil {
err = bosherr.WrapError(err, "Waiting for dig command")
}
return
}
示例10: runCmd
func runCmd(cmdName string, args []string, cmdHook func(*exec.Cmd)) (stdout, stderr string, err error) {
cmd := exec.Command(cmdName, args...)
cmdString := strings.Join(append([]string{cmdName}, args...), " ")
stdoutWriter := bytes.NewBufferString("")
stderrWriter := bytes.NewBufferString("")
cmd.Stdout = stdoutWriter
cmd.Stderr = stderrWriter
if cmdHook != nil {
cmdHook(cmd)
}
err = cmd.Start()
if err != nil {
err = bosherr.WrapError(err, fmt.Sprintf("Error starting command %s", cmdString))
return
}
err = cmd.Wait()
stdout = string(stdoutWriter.Bytes())
stderr = string(stderrWriter.Bytes())
if err != nil {
err = bosherr.WrapError(err, fmt.Sprintf("Error running command: '%s', stdout: '%s', stderr: '%s'",
cmdString, stdout, stderr))
}
return
}
示例11: TestGenerate
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)
}
}
示例12: TestRenderPlainAndHtmlText
func TestRenderPlainAndHtmlText(t *testing.T) {
plainBody := "你好 from message1, should show in plain text"
htmlBody := "<h2>你好 from message1, should show in html text</h2>"
testDate, _ := time.Parse("2006-Jan-02", "2014-Feb-23")
message := &Message{
From: "[email protected]",
To: []string{"[email protected]", "[email protected]"},
Subject: "这个是第11封from message1, single connection",
PlainBody: bytes.NewBufferString(plainBody),
HtmlBody: bytes.NewBufferString(htmlBody),
Date: testDate,
MessageId: "[email protected]",
}
b, _ := message.RenderData()
recipient := string(b)
if !strings.Contains(recipient, plainBody) {
t.Errorf("should have plain body: %s \n", plainBody)
}
if !strings.Contains(recipient, htmlBody) {
t.Errorf("should have html body: %s \n", htmlBody)
}
if !strings.Contains(recipient, "Date: Sun, 23 Feb 2014 00:00:00 GMT") {
t.Error("Message should have the Date header set")
}
if !strings.Contains(recipient, "Message-Id: <[email protected]>") {
t.Error("Message should have the Message-Id header set")
}
}
示例13: MakeSummary
func MakeSummary(post Mapper, lines int, topCtx mustache.Context) string {
content := post["_content"].(*DocContent).Source
r := bufio.NewReader(bytes.NewBufferString(content))
dst := ""
for lines > 0 {
line, _ := r.ReadString('\n')
dst += line
lines--
if lines == 0 {
for "" != strings.Trim(line, "\r\n\t ") {
line, _ = r.ReadString('\n')
dst += line
}
}
}
str, err := mustache.RenderString(dst, topCtx)
if err != nil {
log.Println("BAD Mustache after Summary cut!")
str, err = mustache.RenderString(dst, topCtx)
if err != nil {
log.Println("BAD Mustache Summary?", err)
str = post["_content"].(*DocContent).Main
}
}
mdParser := markdown.NewParser(&markdown.Extensions{Smart: true})
buf := bytes.NewBuffer(nil)
mdParser.Markdown(bytes.NewBufferString(str), markdown.ToHTML(buf))
return buf.String()
}
示例14: searchColors
func searchColors(text string, clean bool) string {
if text == "" {
return ""
}
closed := true
input := bytes.NewBufferString(text)
output := bytes.NewBufferString("")
for {
i, _, err := input.ReadRune()
if err != nil {
break
}
switch i {
case '{':
closed = replaceColorTags(input, output, clean)
case rune(65533):
continue
default:
output.WriteRune(i)
}
}
if !closed {
output.WriteString(_CODE_RESET)
}
return output.String()
}
示例15: TestClient_syncStreams
func TestClient_syncStreams(t *testing.T) {
client, server := TestPluginRPCConn(t, map[string]Plugin{})
// Create streams for the server that we can talk to
stdout_r, stdout_w := io.Pipe()
stderr_r, stderr_w := io.Pipe()
server.Stdout = stdout_r
server.Stderr = stderr_r
// Start the data copying
var stdout_out, stderr_out bytes.Buffer
stdout := bytes.NewBufferString("stdouttest")
stderr := bytes.NewBufferString("stderrtest")
go client.SyncStreams(&stdout_out, &stderr_out)
go io.Copy(stdout_w, stdout)
go io.Copy(stderr_w, stderr)
// Unfortunately I can't think of a better way to make sure all the
// copies above go through so let's just exit.
time.Sleep(100 * time.Millisecond)
// Close everything, and lets test the result
client.Close()
stdout_w.Close()
stderr_w.Close()
if v := stdout_out.String(); v != "stdouttest" {
t.Fatalf("bad: %s", v)
}
if v := stderr_out.String(); v != "stderrtest" {
t.Fatalf("bad: %s", v)
}
}