示例#1
0
func Test_Static_Options_Logging(t *testing.T) {
	response := httptest.NewRecorder()

	var buffer bytes.Buffer
	m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)}
	m.Map(m.logger)
	m.Map(defaultReturnHandler())

	opt := StaticOptions{}
	m.Use(Static(currentRoot, opt))

	req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil)
	if err != nil {
		t.Error(err)
	}

	m.ServeHTTP(response, req)
	expect(t, response.Code, http.StatusOK)
	expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n")

	// Now without logging
	m.Handlers()
	buffer.Reset()

	// This should disable logging
	opt.SkipLogging = true
	m.Use(Static(currentRoot, opt))

	m.ServeHTTP(response, req)
	expect(t, response.Code, http.StatusOK)
	expect(t, buffer.String(), "")
}
示例#2
0
func TestLoggerIPAddress(t *testing.T) {
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec, e), e)
	buf := new(bytes.Buffer)
	e.Logger().SetOutput(buf)
	ip := "127.0.0.1"
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}

	mw := Logger()

	// With X-Real-IP
	req.Header.Add(echo.XRealIP, ip)
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)

	// With X-Forwarded-For
	buf.Reset()
	req.Header.Del(echo.XRealIP)
	req.Header.Add(echo.XForwardedFor, ip)
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)

	// with req.RemoteAddr
	buf.Reset()
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)
}
示例#3
0
func TestDecompressor(t *testing.T) {
	b := new(bytes.Buffer)
	for _, tt := range zlibTests {
		in := bytes.NewBuffer(tt.compressed)
		zlib, err := NewReaderDict(in, tt.dict)
		if err != nil {
			if err != tt.err {
				t.Errorf("%s: NewReader: %s", tt.desc, err)
			}
			continue
		}
		defer zlib.Close()
		b.Reset()
		n, err := io.Copy(b, zlib)
		if err != nil {
			if err != tt.err {
				t.Errorf("%s: io.Copy: %v want %v", tt.desc, err, tt.err)
			}
			continue
		}
		s := b.String()
		if s != tt.raw {
			t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.desc, n, s, len(tt.raw), tt.raw)
		}
	}
}
示例#4
0
// As long as the fields have the same name and implement the
// interface, we can cross-connect them.  Not sure it's useful
// and may even be bad but it works and it's hard to prevent
// without exposing the contents of the object, which would
// defeat the purpose.
func TestGobEncoderFieldsOfDifferentType(t *testing.T) {
	// first, string in field to byte in field
	b := new(bytes.Buffer)
	enc := NewEncoder(b)
	err := enc.Encode(GobTest1{17, &StringStruct{"ABC"}})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	dec := NewDecoder(b)
	x := new(GobTest0)
	err = dec.Decode(x)
	if err != nil {
		t.Fatal("decode error:", err)
	}
	if x.G.a != 'A' {
		t.Errorf("expected 'A' got %c", x.G.a)
	}
	// now the other direction, byte in field to string in field
	b.Reset()
	err = enc.Encode(GobTest0{17, &ByteStruct{'X'}})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	y := new(GobTest1)
	err = dec.Decode(y)
	if err != nil {
		t.Fatal("decode error:", err)
	}
	if y.G.s != "XYZ" {
		t.Fatalf("expected `XYZ` got %q", y.G.s)
	}
}
示例#5
0
文件: fmt_test.go 项目: vsayer/go
func BenchmarkFprintInt(b *testing.B) {
	var buf bytes.Buffer
	for i := 0; i < b.N; i++ {
		buf.Reset()
		Fprint(&buf, 123456)
	}
}
示例#6
0
func TestSingletons(t *testing.T) {
	b := new(bytes.Buffer)
	enc := NewEncoder(b)
	dec := NewDecoder(b)
	for _, test := range singleTests {
		b.Reset()
		err := enc.Encode(test.in)
		if err != nil {
			t.Errorf("error encoding %v: %s", test.in, err)
			continue
		}
		err = dec.Decode(test.out)
		switch {
		case err != nil && test.err == "":
			t.Errorf("error decoding %v: %s", test.in, err)
			continue
		case err == nil && test.err != "":
			t.Errorf("expected error decoding %v: %s", test.in, test.err)
			continue
		case err != nil && test.err != "":
			if strings.Index(err.Error(), test.err) < 0 {
				t.Errorf("wrong error decoding %v: wanted %s, got %v", test.in, test.err, err)
			}
			continue
		}
		// Get rid of the pointer in the rhs
		val := reflect.ValueOf(test.out).Elem().Interface()
		if !reflect.DeepEqual(test.in, val) {
			t.Errorf("decoding singleton: expected %v got %v", test.in, val)
		}
	}
}
示例#7
0
// buildBenchmark builds the benchmark binary.
func (b *Builder) buildBenchmark(workpath string, update bool) (benchBin, log string, err error) {
	goroot := filepath.Join(workpath, "go")
	gobin := filepath.Join(goroot, "bin", "go") + exeExt
	gopath := filepath.Join(*buildroot, "gopath")
	env := append([]string{
		"GOROOT=" + goroot,
		"GOPATH=" + gopath},
		b.envv()...)
	// First, download without installing.
	args := []string{"get", "-d"}
	if update {
		args = append(args, "-u")
	}
	args = append(args, *benchPath)
	var buildlog bytes.Buffer
	runOpts := []runOpt{runTimeout(*buildTimeout), runEnv(env), allOutput(&buildlog), runDir(workpath)}
	err = run(exec.Command(gobin, args...), runOpts...)
	if err != nil {
		fmt.Fprintf(&buildlog, "go get -d %s failed: %s", *benchPath, err)
		return "", buildlog.String(), err
	}
	// Then, build into workpath.
	benchBin = filepath.Join(workpath, "benchbin") + exeExt
	args = []string{"build", "-o", benchBin, *benchPath}
	buildlog.Reset()
	err = run(exec.Command(gobin, args...), runOpts...)
	if err != nil {
		fmt.Fprintf(&buildlog, "go build %s failed: %s", *benchPath, err)
		return "", buildlog.String(), err
	}
	return benchBin, "", nil
}
示例#8
0
文件: exec_test.go 项目: ray0807/go
func TestComparison(t *testing.T) {
	b := new(bytes.Buffer)
	var cmpStruct = struct {
		Uthree, Ufour uint
		NegOne, Three int
	}{3, 4, -1, 3}
	for _, test := range cmpTests {
		text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
		tmpl, err := New("empty").Parse(text)
		if err != nil {
			t.Fatalf("%q: %s", test.expr, err)
		}
		b.Reset()
		err = tmpl.Execute(b, &cmpStruct)
		if test.ok && err != nil {
			t.Errorf("%s errored incorrectly: %s", test.expr, err)
			continue
		}
		if !test.ok && err == nil {
			t.Errorf("%s did not error", test.expr)
			continue
		}
		if b.String() != test.truth {
			t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
		}
	}
}
示例#9
0
func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {

	var buffer bytes.Buffer
	var fields Fields

	logger := New()
	logger.Out = &buffer
	logger.Formatter = new(JSONFormatter)

	llog := logger.WithField("context", "eating raw fish")

	llog.Info("looks delicious")

	err := json.Unmarshal(buffer.Bytes(), &fields)
	assert.NoError(t, err, "should have decoded first message")
	assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
	assert.Equal(t, fields["msg"], "looks delicious")
	assert.Equal(t, fields["context"], "eating raw fish")

	buffer.Reset()

	llog.Warn("omg it is!")

	err = json.Unmarshal(buffer.Bytes(), &fields)
	assert.NoError(t, err, "should have decoded second message")
	assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
	assert.Equal(t, fields["msg"], "omg it is!")
	assert.Equal(t, fields["context"], "eating raw fish")
	assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")

}
示例#10
0
文件: cookie.go 项目: kpumuk/web.go
// writeCookies writes the wire representation of the cookies
// to w. Each cookie is written on a separate "Cookie: " line.
// This choice is made because HTTP parsers tend to have a limit on
// line-length, so it seems safer to place cookies on separate lines.
func writeCookies(w io.Writer, kk []*http.Cookie) os.Error {
	lines := make([]string, 0, len(kk))
	var b bytes.Buffer
	for _, c := range kk {
		b.Reset()
		n := c.Name
		// TODO(petar): c.Value (below) should be unquoted if it is recognized as quoted
		fmt.Fprintf(&b, "%s=%s", http.CanonicalHeaderKey(n), c.Value)
		if len(c.Path) > 0 {
			fmt.Fprintf(&b, "; $Path=%s", http.URLEscape(c.Path))
		}
		if len(c.Domain) > 0 {
			fmt.Fprintf(&b, "; $Domain=%s", http.URLEscape(c.Domain))
		}
		if c.HttpOnly {
			fmt.Fprintf(&b, "; $HttpOnly")
		}
		lines = append(lines, "Cookie: "+b.String()+"\r\n")
	}
	sort.Strings(lines)
	for _, l := range lines {
		if _, err := io.WriteString(w, l); err != nil {
			return err
		}
	}
	return nil
}
示例#11
0
func putBuffer(buf *bytes.Buffer) {
	if buf.Len() > 1024 {
		return
	}
	buf.Reset()
	bufPool.Put(buf)
}
示例#12
0
// Compare the output of the C-based peg-markdown, which
// is, for each test, available in either a .html or a .mm file accompanying
// the .text file, with the output of this package's Markdown processor.
func compareOutput(w *bytes.Buffer, f Formatter, ext string, textPath string, p *Parser) (err error) {
	var bOrig bytes.Buffer

	r, err := os.Open(textPath)
	if err != nil {
		return
	}
	defer r.Close()

	w.Reset()
	p.Markdown(r, f)

	// replace .text extension by `ext'
	base := textPath[:len(textPath)-len(".text")]
	refPath := base + ext

	r, err = os.Open(refPath)
	if err != nil {
		return
	}
	defer r.Close()
	bOrig.ReadFrom(r)
	if bytes.Compare(bOrig.Bytes(), w.Bytes()) != 0 {
		err = fmt.Errorf("test %q failed", refPath)
	}
	return
}
示例#13
0
func TestWriterDict(t *testing.T) {
	const (
		dict = "hello world"
		text = "hello again world"
	)
	var b bytes.Buffer
	w, err := NewWriter(&b, 5)
	if err != nil {
		t.Fatalf("NewWriter: %v", err)
	}
	w.Write([]byte(dict))
	w.Flush()
	b.Reset()
	w.Write([]byte(text))
	w.Close()

	var b1 bytes.Buffer
	w, _ = NewWriterDict(&b1, 5, []byte(dict))
	w.Write([]byte(text))
	w.Close()

	if !bytes.Equal(b1.Bytes(), b.Bytes()) {
		t.Fatalf("writer wrote %q want %q", b1.Bytes(), b.Bytes())
	}
}
示例#14
0
func TestReaderDict(t *testing.T) {
	const (
		dict = "hello world"
		text = "hello again world"
	)
	var b bytes.Buffer
	w, err := NewWriter(&b, 5)
	if err != nil {
		t.Fatalf("NewWriter: %v", err)
	}
	w.Write([]byte(dict))
	w.Flush()
	b.Reset()
	w.Write([]byte(text))
	w.Close()

	r := NewReaderDict(&b, []byte(dict))
	data, err := ioutil.ReadAll(r)
	if err != nil {
		t.Fatal(err)
	}
	if string(data) != "hello again world" {
		t.Fatalf("read returned %q want %q", string(data), text)
	}
}
示例#15
0
文件: pool.go 项目: TheHippo/abp
// Put returns a buffer that is not longer used to the pool
func (abp *AveragedBufferPool) Put(buf *bytes.Buffer) {
	// rewind buffer to start
	buf.Reset()

	capacity := cap(buf.Bytes())

	abp.lock.RLock()

	if capacity > abp.max {
		// buffer was larger the average. create new one
		buf = bytes.NewBuffer(make([]byte, 0, abp.currentAverage))
	}

	abp.lock.RUnlock()

	select {
	case abp.bufferChannel <- buf:
		// return buffer into channel
	default:
		// channel is full, throw it away
	}

	// send value to calculate new averages
	abp.calcChannel <- capacity
}
示例#16
0
文件: binary_test.go 项目: achanda/go
func TestSliceRoundTrip(t *testing.T) {
	buf := new(bytes.Buffer)
	for _, array := range intArrays {
		src := reflect.ValueOf(array).Elem()
		unsigned := false
		switch src.Index(0).Kind() {
		case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			unsigned = true
		}
		for i := 0; i < src.Len(); i++ {
			if unsigned {
				src.Index(i).SetUint(uint64(i * 0x07654321))
			} else {
				src.Index(i).SetInt(int64(i * 0x07654321))
			}
		}
		buf.Reset()
		srcSlice := src.Slice(0, src.Len())
		err := Write(buf, BigEndian, srcSlice.Interface())
		if err != nil {
			t.Fatal(err)
		}
		dst := reflect.New(src.Type()).Elem()
		dstSlice := dst.Slice(0, dst.Len())
		err = Read(buf, BigEndian, dstSlice.Interface())
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(src.Interface(), dst.Interface()) {
			t.Fatal(src)
		}
	}
}
示例#17
0
func TestEventWriter(t *testing.T) {
	cases := []struct {
		m   Event
		exp string
	}{
		{
			m: Event{
				ID:    "1",
				Event: "test\nevent",
				Data:  "hello\nworld",
			},
			exp: "id: 1\nevent: testevent\ndata: hello\ndata: world\n\n",
		},
	}

	var buf bytes.Buffer

	for _, c := range cases {

		buf.Reset()
		err := WriteEvent(&buf, c.m)

		if err != nil {
			t.Fatal(err)
		}

		exp := c.exp
		got := buf.String()
		if exp != got {
			t.Error("\nExp", exp, "\nGot", got)
		}
	}

}
示例#18
0
文件: rat_test.go 项目: Sunmonds/gcc
func TestRatGobEncoding(t *testing.T) {
	var medium bytes.Buffer
	enc := gob.NewEncoder(&medium)
	dec := gob.NewDecoder(&medium)
	for i, test := range gobEncodingTests {
		for j := 0; j < 4; j++ {
			medium.Reset() // empty buffer for each test case (in case of failures)
			stest := test
			if j&1 != 0 {
				// negative numbers
				stest = "-" + test
			}
			if j%2 != 0 {
				// fractions
				stest = stest + "." + test
			}
			var tx Rat
			tx.SetString(stest)
			if err := enc.Encode(&tx); err != nil {
				t.Errorf("#%d%c: encoding failed: %s", i, 'a'+j, err)
			}
			var rx Rat
			if err := dec.Decode(&rx); err != nil {
				t.Errorf("#%d%c: decoding failed: %s", i, 'a'+j, err)
			}
			if rx.Cmp(&tx) != 0 {
				t.Errorf("#%d%c: transmission failed: got %s want %s", i, 'a'+j, &rx, &tx)
			}
		}
	}
}
示例#19
0
func (r *registry) giveBuf(buf *bytes.Buffer) {
	buf.Reset()
	select {
	case r.bufPool <- buf:
	default:
	}
}
示例#20
0
func TestLoggerMiddleware(t *testing.T) {
	var buf bytes.Buffer
	Logger = log.New(&buf, "", 0)

	router := New(Context{})
	router.Middleware(LoggerMiddleware)
	router.Get("/action", (*Context).A)

	// Hit an action:
	rw, req := newTestRequest("GET", "/action")
	router.ServeHTTP(rw, req)
	assertResponse(t, rw, "context-A", 200)

	// Make sure our buf has something good:
	logRegexp := regexp.MustCompile("\\[\\d+ .{2}\\] 200 '/action'")
	if !logRegexp.MatchString(buf.String()) {
		t.Error("Got invalid log entry: ", buf.String())
	}

	// Do a 404:
	buf.Reset()
	rw, req = newTestRequest("GET", "/wat")
	router.ServeHTTP(rw, req)
	assertResponse(t, rw, "Not Found", 404)

	// Make sure our buf has something good:
	logRegexpNotFound := regexp.MustCompile("\\[\\d+ .{2}\\] 404 '/wat'")
	if !logRegexpNotFound.MatchString(buf.String()) {
		t.Error("Got invalid log entry: ", buf.String())
	}
}
示例#21
0
func TestGobEncoderField(t *testing.T) {
	b := new(bytes.Buffer)
	// First a field that's a structure.
	enc := NewEncoder(b)
	err := enc.Encode(GobTest0{17, &ByteStruct{'A'}})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	dec := NewDecoder(b)
	x := new(GobTest0)
	err = dec.Decode(x)
	if err != nil {
		t.Fatal("decode error:", err)
	}
	if x.G.a != 'A' {
		t.Errorf("expected 'A' got %c", x.G.a)
	}
	// Now a field that's not a structure.
	b.Reset()
	gobber := Gobber(23)
	err = enc.Encode(GobTest3{17, &gobber})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	y := new(GobTest3)
	err = dec.Decode(y)
	if err != nil {
		t.Fatal("decode error:", err)
	}
	if *y.G != 23 {
		t.Errorf("expected '23 got %d", *y.G)
	}
}
示例#22
0
文件: cgo.go 项目: nakalsio/gb
// call pkg-config and return the cflags and ldflags.
func pkgconfig(p *Package) ([]string, []string, error) {
	if len(p.CgoPkgConfig) == 0 {
		return nil, nil, nil // nothing to do
	}
	args := []string{
		"--cflags",
	}
	args = append(args, p.CgoPkgConfig...)
	var out bytes.Buffer
	err := p.runOut(&out, p.Dir, nil, "pkg-config", args...)
	if err != nil {
		return nil, nil, err
	}
	cflags := strings.Fields(out.String())

	args = []string{
		"--libs",
	}
	args = append(args, p.CgoPkgConfig...)
	out.Reset()
	err = p.runOut(&out, p.Dir, nil, "pkg-config", args...)
	if err != nil {
		return nil, nil, err
	}
	ldflags := strings.Fields(out.String())
	return cflags, ldflags, nil
}
示例#23
0
func TestGobEncoderFieldTypeError(t *testing.T) {
	// GobEncoder to non-decoder: error
	b := new(bytes.Buffer)
	enc := NewEncoder(b)
	err := enc.Encode(GobTest1{17, &StringStruct{"ABC"}})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	dec := NewDecoder(b)
	x := &GobTest2{}
	err = dec.Decode(x)
	if err == nil {
		t.Fatal("expected decode error for mismatched fields (encoder to non-decoder)")
	}
	if strings.Index(err.Error(), "type") < 0 {
		t.Fatal("expected type error; got", err)
	}
	// Non-encoder to GobDecoder: error
	b.Reset()
	err = enc.Encode(GobTest2{17, "ABC"})
	if err != nil {
		t.Fatal("encode error:", err)
	}
	y := &GobTest1{}
	err = dec.Decode(y)
	if err == nil {
		t.Fatal("expected decode error for mismatched fields (non-encoder to decoder)")
	}
	if strings.Index(err.Error(), "type") < 0 {
		t.Fatal("expected type error; got", err)
	}
}
示例#24
0
func ExampleClient_AttachToContainer() {
	client, err := docker.NewClient("http://localhost:4243")
	if err != nil {
		log.Fatal(err)
	}
	client.SkipServerVersionCheck = true
	// Reading logs from container a84849 and sending them to buf.
	var buf bytes.Buffer
	err = client.AttachToContainer(docker.AttachToContainerOptions{
		Container:    "a84849",
		OutputStream: &buf,
		Logs:         true,
		Stdout:       true,
		Stderr:       true,
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println(buf.String())
	buf.Reset()
	err = client.AttachToContainer(docker.AttachToContainerOptions{
		Container:    "a84849",
		OutputStream: &buf,
		Stdout:       true,
		Stream:       true,
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println(buf.String())
}
示例#25
0
// parseMultivalueLine parses a line that includes several quoted values separated by whitespaces.
// Example: MachineMetadata="foo=bar" "baz=qux"
// If the provided line is not a multivalue string, the line is returned as the sole value.
func parseMultivalueLine(line string) (values []string) {
	if !strings.HasPrefix(line, `"`) || !strings.HasSuffix(line, `"`) {
		return []string{line}
	}

	var v bytes.Buffer
	w := false // check whether we're within quotes or not
	for _, e := range []byte(line) {
		// ignore quotes
		if e == '"' {
			w = !w
			continue
		}

		if e == ' ' {
			if !w { // between quoted values, keep the previous value and reset.
				values = append(values, v.String())
				v.Reset()
				continue
			}
		}

		v.WriteByte(e)
	}

	values = append(values, v.String())

	return
}
示例#26
0
func readSlidesDat() (slides []string, err error) {
	f, err := os.Open("slides.dat")
	if err != nil {
		return
	}
	defer f.Close()
	var buf bytes.Buffer
	flush := func() {
		s := strings.TrimSpace(buf.String())
		if s != "" {
			slides = append(slides, s+"\n")
		}
		buf.Reset()
	}
	bs := bufio.NewScanner(f)
	for bs.Scan() {
		if bs.Text() == "--" {
			flush()
			continue
		}
		buf.WriteString(bs.Text())
		buf.WriteByte('\n')
	}
	flush()
	return slides, bs.Err()
}
示例#27
0
文件: path.go 项目: ssrl/go
// EvalSymlinks returns the path name after the evaluation of any symbolic
// links.
// If path is relative it will be evaluated relative to the current directory.
func EvalSymlinks(path string) (string, os.Error) {
	if runtime.GOOS == "windows" {
		// Symlinks are not supported under windows.
		_, err := os.Lstat(path)
		if err != nil {
			return "", err
		}
		return Clean(path), nil
	}
	const maxIter = 255
	originalPath := path
	// consume path by taking each frontmost path element,
	// expanding it if it's a symlink, and appending it to b
	var b bytes.Buffer
	for n := 0; path != ""; n++ {
		if n > maxIter {
			return "", os.NewError("EvalSymlinks: too many links in " + originalPath)
		}

		// find next path component, p
		i := strings.IndexRune(path, Separator)
		var p string
		if i == -1 {
			p, path = path, ""
		} else {
			p, path = path[:i], path[i+1:]
		}

		if p == "" {
			if b.Len() == 0 {
				// must be absolute path
				b.WriteRune(Separator)
			}
			continue
		}

		fi, err := os.Lstat(b.String() + p)
		if err != nil {
			return "", err
		}
		if !fi.IsSymlink() {
			b.WriteString(p)
			if path != "" {
				b.WriteRune(Separator)
			}
			continue
		}

		// it's a symlink, put it at the front of path
		dest, err := os.Readlink(b.String() + p)
		if err != nil {
			return "", err
		}
		if IsAbs(dest) {
			b.Reset()
		}
		path = dest + string(Separator) + path
	}
	return Clean(b.String()), nil
}
示例#28
0
func (s *ESAPIV0) Bulk(data *bytes.Buffer) {
	if data == nil || data.Len() == 0 {
		return
	}
	data.WriteRune('\n')
	url := fmt.Sprintf("%s/_bulk", s.Host)

	client := &http.Client{}
	reqest, _ := http.NewRequest("POST", url, data)
	if s.Auth != nil {
		reqest.SetBasicAuth(s.Auth.User, s.Auth.Pass)
	}
	resp, errs := client.Do(reqest)
	if errs != nil {
		log.Error(errs)
		return
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Error(err)
		return
	}
	log.Trace(url, string(body))
	defer resp.Body.Close()
	defer data.Reset()
	if resp.StatusCode != 200 {
		log.Errorf("bad bulk response: %s %s", body, resp.StatusCode)
		return
	}
}
示例#29
0
// Get retrieves the credentials for a given server url.
// The reader must contain the server URL to search.
// The writer is used to write the JSON serialization of the credentials.
func Get(helper Helper, reader io.Reader, writer io.Writer) error {
	scanner := bufio.NewScanner(reader)

	buffer := new(bytes.Buffer)
	for scanner.Scan() {
		buffer.Write(scanner.Bytes())
	}

	if err := scanner.Err(); err != nil && err != io.EOF {
		return err
	}

	serverURL := strings.TrimSpace(buffer.String())

	username, secret, err := helper.Get(serverURL)
	if err != nil {
		return err
	}

	resp := Credentials{
		Username: username,
		Secret:   secret,
	}

	buffer.Reset()
	if err := json.NewEncoder(buffer).Encode(resp); err != nil {
		return err
	}

	fmt.Fprint(writer, buffer.String())
	return nil
}
示例#30
0
// runBenchmarkInsert benchmarks inserting count rows into a table.
func runBenchmarkInsert(b *testing.B, db *gosql.DB, count int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.insert`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.insert (k INT PRIMARY KEY)`); err != nil {
		b.Fatal(err)
	}
	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.insert`); err != nil {
			b.Fatal(err)
		}
	}()

	b.ResetTimer()
	var buf bytes.Buffer
	val := 0
	for i := 0; i < b.N; i++ {
		buf.Reset()
		buf.WriteString(`INSERT INTO bench.insert VALUES `)
		for j := 0; j < count; j++ {
			if j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, "(%d)", val)
			val++
		}
		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()

}