func (c *Conn) cget(name string) (data []byte, err error) { cache := filepath.Join(c.cache, name) f, err := os.Open(cache) if err == nil { defer f.Close() return ioutil.ReadAll(f) } if altCache := c.altCachePath(name); altCache != "" { f, err := os.Open(altCache) if err == nil { defer f.Close() return ioutil.ReadAll(f) } } data, err = c.bget(name) if err != nil { return nil, err } dir, _ := filepath.Split(cache) os.MkdirAll(dir, 0700) ioutil.WriteFile(cache, data, 0600) return data, nil }
func (s *archiveDataSuite) SetUpTest(c *gc.C) { s.IsolationSuite.SetUpTest(c) meta, err := backups.NewMetadataJSONReader(bytes.NewBufferString(`{` + `"ID":"20140909-115934.asdf-zxcv-qwe",` + `"Checksum":"123af2cef",` + `"ChecksumFormat":"SHA-1, base64 encoded",` + `"Size":10,` + `"Stored":"0001-01-01T00:00:00Z",` + `"Started":"2014-09-09T11:59:34Z",` + `"Finished":"2014-09-09T12:00:34Z",` + `"Notes":"",` + `"Environment":"asdf-zxcv-qwe",` + `"Machine":"0",` + `"Hostname":"myhost",` + `"Version":"1.21-alpha3"` + `}` + "\n")) c.Assert(err, jc.ErrorIsNil) archiveFile := s.newArchiveFile(c, meta) compressed, err := ioutil.ReadAll(archiveFile) c.Assert(err, jc.ErrorIsNil) gzr, err := gzip.NewReader(bytes.NewBuffer(compressed)) c.Assert(err, jc.ErrorIsNil) data, err := ioutil.ReadAll(gzr) c.Assert(err, jc.ErrorIsNil) s.archiveFile = bytes.NewBuffer(compressed) s.data = data s.meta = meta }
func TestPurge(t *testing.T) { appId := config.ApplicationId dataPath := "/resin-data/" + appId if err := ioutil.WriteFile(dataPath+"/test", []byte("test"), 0777); err != nil { t.Fatal("Could not create test file for purge") } else if request, err := http.NewRequest("POST", supervisorAddress+"/v1/purge?apikey=bananas", strings.NewReader(`{"appId": "`+appId+`"}`)); err != nil { t.Fatal(err) } else { request.Header.Set("Content-Type", "application/json") response, err := http.DefaultClient.Do(request) defer response.Body.Close() if err != nil { t.Fatal(err) } else if response.StatusCode != http.StatusOK { t.Errorf("Expected 200, got %d", response.StatusCode) if contents, err := ioutil.ReadAll(response.Body); err != nil { t.Fatal(err) } else { t.Fatalf("Response: %s", contents) } } else { if contents, err := ioutil.ReadAll(response.Body); err != nil { t.Fatal(err) } else if !strings.EqualFold(string(contents), `{"Data":"OK","Error":""}`) { t.Errorf("Purge response didn't match the expected JSON, got: %s", contents) } if dirContents, err := ioutil.ReadDir(dataPath); err != nil { t.Errorf("Could not read the data path after purge: %s", err) } else if len(dirContents) > 0 { t.Error("Data directory not empty after purge") } } } }
func readBody(contentEncoding string, body io.Reader) ([]byte, error) { var err error result := []byte{} if contentEncoding == "gzip" { reader, err := gzip.NewReader(body) if err != nil { return result, werrors.NewDetails(ErrReadGZipResponse, err) } result, err = ioutil.ReadAll(reader) if err == nil { err = reader.Close() } else { _ = reader.Close() } if err != nil { return result, werrors.NewDetails(ErrReadGZipResponse, err) } } else if contentEncoding == "identity" || contentEncoding == "" { result, err = ioutil.ReadAll(body) if err != nil { return result, werrors.NewDetails(ErrReadResponse, err) } } else { return result, werrors.NewFields(ErrUnknownContentEncoding, zap.String("encoding", contentEncoding)) } return result, nil }
func TestStacktracing(test *testing.T) { logBuffer := new(bytes.Buffer) logger := &Logger{ Prefix: "slogger.logger_test", Appenders: []Appender{NewStringAppender(logBuffer)}, } _, err := addZero(6, 0, logger) if err != nil { logger.Stackf(WARN, err, "Had an illegal argument to addZero. %d", 0) } logOutput, _ := ioutil.ReadAll(logBuffer) if len(logOutput) > 0 { test.Errorf("Did not expect any log messages from this first call.") } _, err = addZero(5, 2, logger) if err != nil { logger.Stackf(WARN, err, "Had an illegal argument to addZero. %d", 2) } logOutput, _ = ioutil.ReadAll(logBuffer) if len(logOutput) == 0 { test.Errorf("Expected a log message when adding 2.") } _, err = addZero(-8, -4, logger) if err != nil { logger.Stackf(WARN, err, "Had an illegal argument to addZero. %d", -4) } logOutput, _ = ioutil.ReadAll(logBuffer) if len(logOutput) == 0 { test.Errorf("Expected a log message when adding -4.") } }
func TestUnCompressed(t *testing.T) { assert := assert.New(t) // SELECT repeat("a", 50) before := ` 09 00 00 00 03 53 45 4c 45 43 54 20 31 ....SELECT 1 ` after := ` 0d 00 00 00 00 00 00 09 00 00 00 03 53 45 4c 45 ............SELE 43 54 20 31 CT 1 ` _, _ = before, after buf := bytes.NewBufferString("") buf.Write(DecodeDump(after)) r := NewCompressedReader(buf) b, err := ioutil.ReadAll(r) assert.NoError(err) assert.EqualValues(DecodeDump(before), b) // write and read again w := NewCompressedWriter(buf) _, err = w.Write(DecodeDump(before)) assert.NoError(err) b, err = ioutil.ReadAll(r) assert.NoError(err) assert.EqualValues(DecodeDump(before), b) }
func (c *Client) get(fullUrl string, query string) (string, error) { getUrl, err := url.Parse(fullUrl) if err != nil { return "", fmt.Errorf("pusher: GET failed: %s", err) } getUrl.Scheme = c.scheme() getUrl.RawQuery = query resp, err := HttpClient.Get(getUrl.String()) if err != nil { return "", fmt.Errorf("pusher: GET failed: %s", err) } defer resp.Body.Close() if resp.StatusCode >= 400 { b, _ := ioutil.ReadAll(resp.Body) return "", fmt.Errorf("pusher: GET failed: %s", b) } fullBody, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("pusher: GET failed: %s", err) } return string(fullBody), nil }
// handle http req & response to netplugin func (cniApp *cniAppInfo) handleHTTP(url string, jsonReq *bytes.Buffer) int { cniLog.Infof("http POST url: %s data: %v", url, jsonReq) httpResp, err := cniApp.httpClient.Post(url, "application/json", jsonReq) if err != nil { return cniApp.sendCniErrorResp("failed to get response from netplugin :" + err.Error()) } defer httpResp.Body.Close() switch httpResp.StatusCode { case http.StatusOK: cniLog.Infof("received http OK reponse from netplugin") info, err := ioutil.ReadAll(httpResp.Body) if err != nil { return cniApp.sendCniErrorResp("failed to read success response from netplugin :" + err.Error()) } return cniApp.sendCniResp(info, cniapi.CniStatusSuccess) case http.StatusInternalServerError: cniLog.Infof("received http error reponse from netplugin") info, err := ioutil.ReadAll(httpResp.Body) if err != nil { return cniApp.sendCniErrorResp("failed to read error response from netplugin :" + err.Error()) } return cniApp.sendCniResp(info, cniapi.CniStatusErrorUnsupportedField) default: cniLog.Infof("received unknown error from netplugin") return cniApp.sendCniErrorResp("error response from netplugin: " + http.StatusText(httpResp.StatusCode)) } }
func captureOutputs(f func()) (stdout, stderr []byte) { oldStdout := os.Stdout oldStderr := os.Stderr rOut, wOut, _ := os.Pipe() rErr, wErr, _ := os.Pipe() os.Stdout = wOut os.Stderr = wErr resetLoggers() f() outC := make(chan []byte) errC := make(chan []byte) go func() { bytes, _ := ioutil.ReadAll(rOut) outC <- bytes bytes, _ = ioutil.ReadAll(rErr) errC <- bytes }() wOut.Close() wErr.Close() stdout = <-outC stderr = <-errC os.Stdout = oldStdout os.Stderr = oldStderr return }
func GetItem(getItemRequest GetItemRequest, userId string, userSecert string, region string) (map[string]Attribute, error) { query, err := json.Marshal(getItemRequest) if err != nil { return nil, err } response, err := makeRequest("http://dynamodb."+region+".amazonaws.com/", string(query[:]), "GetItem", userId, userSecert, region) if err != nil { return nil, err } defer response.Body.Close() if response.StatusCode != 200 { content, _ := ioutil.ReadAll(response.Body) var errorResponse aws.ErrorStruct json.Unmarshal(content, &errorResponse) return nil, errors.New("Unable to register device. " + errorResponse.Type + ": " + errorResponse.Message) } else { content, _ := ioutil.ReadAll(response.Body) items := make(map[string]map[string]Attribute) json.Unmarshal(content, &items) return items["Item"], nil } }
func ScanForItems(scanRequest ScanRequest, userId string, userSecert string, region string) (*ScanResponse, error) { query, err := json.Marshal(scanRequest) if err != nil { return nil, err } response, err := makeRequest("http://dynamodb."+region+".amazonaws.com/", string(query[:]), "Scan", userId, userSecert, region) if err != nil { return nil, err } defer response.Body.Close() if response.StatusCode != 200 { content, _ := ioutil.ReadAll(response.Body) var errorResponse aws.ErrorStruct json.Unmarshal(content, &errorResponse) return nil, errors.New("Unable to register device. " + errorResponse.Type + ": " + errorResponse.Message) } else { content, _ := ioutil.ReadAll(response.Body) scanResponse := new(ScanResponse) json.Unmarshal(content, scanResponse) return scanResponse, nil } }
func RunClang(stdin string, args ...string) ([]byte, []byte, error) { cmd := exec.Command("clang", args...) log4go.Debug("Running clang command: %v", cmd) if in, err := cmd.StdinPipe(); err != nil { return nil, nil, err } else if e, err := cmd.StderrPipe(); err != nil { return nil, nil, err } else if s, err := cmd.StdoutPipe(); err != nil { return nil, nil, err } else if err := cmd.Start(); err != nil { return nil, nil, err } else { in.Write([]byte(stdin)) in.Close() so, serr := ioutil.ReadAll(s) eo, eerr := ioutil.ReadAll(e) // We ignore the output error here as a non-zero exit // code doesn't necessarily mean that the output isn't // useful cmd.Wait() log4go.Fine("stdout: %s\n", string(so)) log4go.Fine("stderr: %s\n", string(eo)) if serr != nil { return so, eo, serr } else if eerr != nil { return so, eo, eerr } return so, eo, nil } }
// Post performs an http POST of the given bytes to the given relative URL. Any // response returned from the request will be returned from this method as a // byte slice. func (ths *TestHTTPSession) Post(relative string, body []byte) []byte { req, err := http.NewRequest("POST", ths.baseURL+relative, bytes.NewBuffer(body)) if err != nil { ths.t.Fatal(err) } // All requests currently accept JSON. req.Header.Set(util.ContentTypeHeader, util.JSONContentType) req.Header.Set(util.AcceptHeader, util.JSONContentType) resp, err := ths.client.Do(req) if err != nil { ths.t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) ths.t.Fatalf("unexpected status code: %v, %s", resp.StatusCode, body) } returnedContentType := resp.Header.Get(util.ContentTypeHeader) if returnedContentType != util.JSONContentType { ths.t.Fatalf("unexpected content type: %v", returnedContentType) } respBody, err := ioutil.ReadAll(resp.Body) if err != nil { ths.t.Fatal(err) } return respBody }
func responseCert(client *http.Client, res *http.Response, bundle bool) ([][]byte, error) { b, err := ioutil.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf("acme: response stream: %v", err) } cert := [][]byte{b} if !bundle { return cert, nil } // append ca cert up := linkHeader(res.Header, "up") if up == "" { return nil, errors.New("acme: rel=up link not found") } res, err = client.Get(up) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, responseError(res) } b, err = ioutil.ReadAll(res.Body) if err != nil { return nil, err } return append(cert, b), nil }
func getOathToken(userID string, userCode string) { fmt.Println("Getting the OAuthToken") //CHANGE FROM LOCALHOST requestString := "https://foursquare.com/oauth2/access_token?client_id=5ATHFEOTK5EU23DGQXCJ4XHYF1OWTBDIIV2CHXBAYQN0X5IO&client_secret=F1SZ1YRLHF4RURVU40QTC5NCB4Y3AHPM4MMIXHFDCRZZD4R0&grant_type=authorization_code&redirect_uri=https://localhost/afterlanding.html&code=" + userCode fmt.Println(requestString) response, err := http.Get(requestString) if response.StatusCode != 200 { fmt.Println("error") body, _ := ioutil.ReadAll(response.Body) fmt.Println("Body: ", string(body)) return } check(err) body, _ := ioutil.ReadAll(response.Body) fmt.Println("Body: ", string(body)) strings := strings.SplitAfter(string(body), ":") fmt.Println("Strings after Split: ", strings) session, err := mgo.Dial("localhost") check(err) defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("test").C("foursqare") toInsert := foursquareInformation{userID, strings[1], make([]string, 0), make([]string, 0)} c.Insert(&toInsert) //I presume we would here go get the user's data }
func (pbp *PBP) Read(rc io.ReadCloser) error { binary.Read(rc, binary.LittleEndian, &pbp.cookie) if pbp.cookie == 0x464C457f { fmt.Printf("File is an elf, converting to empty PBP") bytes, _ := ioutil.ReadAll(rc) pbp.data[6] = append([]byte{0x7f, 0x45, 0x4c, 0x46}[:], bytes...) pbp.cookie = 0x50425000 pbp.version = 0x00010000 return nil } if pbp.cookie != 0x50425000 { return errors.New("bad cookie") } binary.Read(rc, binary.LittleEndian, &pbp.version) for i := 0; i < 8; i++ { binary.Read(rc, binary.LittleEndian, &pbp.offsets[i]) } for i := 0; i < 7; i++ { pbp.data[i] = make([]byte, pbp.offsets[i+1]-pbp.offsets[i]) if len(pbp.data[i]) > 0 { _, err := rc.Read(pbp.data[i]) if err != nil { return err } } } var err error pbp.data[7], err = ioutil.ReadAll(rc) return err }
// Parse parses a profile and checks for its validity. The input // may be a gzip-compressed encoded protobuf or one of many legacy // profile formats which may be unsupported in the future. func Parse(r io.Reader) (*Profile, error) { orig, err := ioutil.ReadAll(r) if err != nil { return nil, err } var p *Profile if len(orig) >= 2 && orig[0] == 0x1f && orig[1] == 0x8b { var data []byte if gz, err := gzip.NewReader(bytes.NewBuffer(orig)); err == nil { data, err = ioutil.ReadAll(gz) } if err != nil { return nil, fmt.Errorf("decompressing profile: %v", err) } orig = data } if p, err = parseUncompressed(orig); err != nil { if p, err = parseLegacy(orig); err != nil { return nil, fmt.Errorf("parsing profile: %v", err) } } if err := p.CheckValid(); err != nil { return nil, fmt.Errorf("malformed profile: %v", err) } return p, nil }
func GetMessages(secret, deviceid string) (mr *MessagesResponse, err error) { pform := url.Values{} pform.Add("secret", secret) pform.Add("device_id", deviceid) // fmt.Printf("Requesting messages with %s\n", pform.Encode()) resp, err := http.Get("https://api.pushover.net/1/messages.json?" + pform.Encode()) if err != nil { return } if resp.StatusCode == 200 { var jbuf []byte jbuf, err = ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read from body: %s", err) return } mr = &MessagesResponse{} jerr := json.Unmarshal(jbuf, mr) if jerr != nil { fmt.Printf("Bad unmarshal: [%s]\n", jerr) return } // fmt.Printf("M is %d %t %+v\n", mr.APIResponse.Status, mr.User.DesktopLicense, *mr) } else { b, _ := ioutil.ReadAll(resp.Body) err = fmt.Errorf("Bad Messages response from pushover: %s\n%s", resp.Status, b) } return }
func (s *s3Source) Open() (io.Reader, error) { if s.cachedResponse == nil { var e error client := s3Client() logger.Printf("using client %#v", client) logger.Printf("opening key=%s bucket=%s", s.key, s.bucket) s.cachedResponse, e = client.Get(s.bucket, s.key) if e != nil { var b []byte if s.cachedResponse != nil { var err error b, err = ioutil.ReadAll(s.cachedResponse.Body) if err != nil { return nil, err } } return nil, fmt.Errorf("error getting key: %s: %s", e, b) } if s.cachedResponse.Status[0] != '2' { b, err := ioutil.ReadAll(s.cachedResponse.Body) if err != nil { return nil, err } return nil, fmt.Errorf("expected status 2xx, got %s: %s", s.cachedResponse.Status, b) } } return s.cachedResponse.Body, nil }
func TestEncryptData(t *testing.T) { for _, test := range []struct { in []byte expected []byte }{ {[]byte{}, file0}, {[]byte{1}, file1}, {[]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, file16}, } { c, err := newCipher(NameEncryptionStandard, "", "") assert.NoError(t, err) c.cryptoRand = newRandomSource(1E8) // nodge the crypto rand generator // Check encode works buf := bytes.NewBuffer(test.in) encrypted, err := c.EncryptData(buf) assert.NoError(t, err) out, err := ioutil.ReadAll(encrypted) assert.NoError(t, err) assert.Equal(t, test.expected, out) // Check we can decode the data properly too... buf = bytes.NewBuffer(out) decrypted, err := c.DecryptData(ioutil.NopCloser(buf)) assert.NoError(t, err) out, err = ioutil.ReadAll(decrypted) assert.NoError(t, err) assert.Equal(t, test.in, out) } }
// a workaround because http POST following redirection misses request body func postFollowingOneRedirect(target string, contentType string, b *bytes.Buffer) error { backupReader := bytes.NewReader(b.Bytes()) resp, err := http.Post(target, contentType, b) if err != nil { return err } defer resp.Body.Close() reply, _ := ioutil.ReadAll(resp.Body) statusCode := resp.StatusCode if statusCode == http.StatusMovedPermanently { var urlStr string if urlStr = resp.Header.Get("Location"); urlStr == "" { return fmt.Errorf("%d response missing Location header", resp.StatusCode) } glog.V(0).Infoln("Post redirected to ", urlStr) resp2, err2 := http.Post(urlStr, contentType, backupReader) if err2 != nil { return err2 } defer resp2.Body.Close() reply, _ = ioutil.ReadAll(resp2.Body) statusCode = resp2.StatusCode } glog.V(0).Infoln("Post returned status: ", statusCode, string(reply)) if statusCode != http.StatusOK { return errors.New(string(reply)) } return nil }
func Auth(url, userw, passw string) (ClmService, error) { fmt.Println("Auth:", url) c := ClmService{} c.URL = url url = url + AUTH_ACTION fmt.Println("Auth:", url, userw) type AuthJson struct { Name string `json:"username"` Password string `json:"password"` } group := AuthJson{ Name: userw, Password: passw, } b, err := json.Marshal(group) if err != nil { fmt.Println("Auth: error:", err) return c, err } os.Stdout.Write(b) jsonStr := b req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") fmt.Println("Auth: req=%s", req, "\n") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Auth: client.Do req:%s", req, err) return c, err } var status int if (err == nil) && (resp.StatusCode == 200) { status = UP } else { status = DOWN } fmt.Println("Auth: StatusCode: %s status:", resp.StatusCode, status) defer resp.Body.Close() fmt.Println("Auth: response Status:", resp.Status) fmt.Println("Auth: response Headers:", resp.Header) contents, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Auth: ioutil.ReadAll err:%s", err) return c, err } fmt.Printf("Auth: response Contents:%s\n", string(contents)) token := resp.Header[AUTHORIZATION_TOKEN] fmt.Println("Auth: token:", token) if token == nil { fmt.Println("Auth: no auth token receieved") c.authtoken = "aaa" return c, fmt.Errorf("No auth token") } c.authtoken = token[0] fmt.Println("Auth: Token:", token, c.authtoken) body, _ := ioutil.ReadAll(resp.Body) fmt.Println("Auth: Response Body:", string(body)) return c, nil }
func TestImportImageShouldPassTarContentToBodyWhenSourceIsFilePath(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer tarPath := "testing/data/container.tar" opts := ImportImageOptions{ Source: tarPath, Repository: "testimage", OutputStream: &buf, } err := client.ImportImage(opts) if err != nil { t.Fatal(err) } tar, err := os.Open(tarPath) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] tarContent, err := ioutil.ReadAll(tar) body, err := ioutil.ReadAll(req.Body) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(tarContent, body) { t.Errorf("ImportImage: wrong body. Want %#v content. Got %#v.", tarPath, body) } }
func GetLanIP_Openwrt(address, password string) string { // Login first jar, _ := cookiejar.New(nil) client := &http.Client{Jar: jar} res, err := client.PostForm("http://"+address+"/", url.Values{"luci_username": {"root"}, "luci_password": {password}}) if err != nil { fmt.Println(err) return "" } bin, _ := ioutil.ReadAll(res.Body) res.Body.Close() str := string(bin) ex := regexp.MustCompile(`/cgi-bin/luci/;stok=([a-z0-9]{32})`) // /cgi-bin/luci/;stok=dfc41c0ba4035a36922a6df4e26f6dd7/ li := ex.FindStringSubmatch(str) if len(li) > 1 { res, err = client.Get("http://" + address + li[0] + "?status=1") if err != nil { fmt.Println(err) return "" } bin, _ = ioutil.ReadAll(res.Body) res.Body.Close() str = string(bin) ex = regexp.MustCompile(`"ipaddr":"(10\.[\.0-9]+?)",`) li = ex.FindStringSubmatch(str) if len(li) > 1 { return li[1] } } return "" }
func RegisterDevice(token string, customData string, userId string, userSecret string, region string, applicationArn string) (arn string, err error) { values := url.Values{} values.Set("Action", "CreatePlatformEndpoint") values.Set("CustomUserData", customData) values.Set("Token", token) values.Set("PlatformApplicationArn", applicationArn) values.Set("Timestamp", time.Now().UTC().Format(time.RFC3339)) response, err := makeRequest("http://sns."+region+".amazonaws.com/", values, userId, userSecret, region) if err != nil { return "", err } defer response.Body.Close() if response.StatusCode != 200 { content, _ := ioutil.ReadAll(response.Body) var errorResponse aws.ErrorResponse xml.Unmarshal(content, &errorResponse) return "", errors.New("Unable to register device. " + errorResponse.Error.Code + ": " + errorResponse.Error.Message) } else { content, _ := ioutil.ReadAll(response.Body) var createResponse CreateResponse xml.Unmarshal(content, &createResponse) return createResponse.CreatePlatformEndpointResult.EndpointArn, nil } }
// Create a HypeDNS name for this device func setHypeDNS(hostname string) (response string, err error) { setLoc := "/_hypehost/set?hostname=" getLoc := "/_hypehost/get" nodeInfoHost := "http://[fc5d:baa5:61fc:6ffd:9554:67f0:e290:7535]:8000" if len(hostname) == 0 { // The request is a "get" resp, err := http.Get(nodeInfoHost + getLoc) if err != nil { fmt.Println("Got an error, %s", err) err = fmt.Errorf("Got an error when attempting to retrieve " + "hostname. This is usually because you can't connect to HypeDNS. " + "Try again later") return "", err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println("You are: " + string(body)) return "", nil } // The request is a "set" resp, err := http.Get(nodeInfoHost + setLoc + hostname) if err != nil { fmt.Println("Got an error, %s", err) err = fmt.Errorf("Got an error when attempting to change hostname. " + "Try again later") return "", err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println("Hostname " + string(body) + " created.") return "", nil }
func sockRequest(method, endpoint string) ([]byte, error) { // FIX: the path to sock should not be hardcoded sock := filepath.Join("/", "var", "run", "docker.sock") c, err := net.DialTimeout("unix", sock, time.Duration(10*time.Second)) if err != nil { return nil, fmt.Errorf("could not dial docker sock at %s: %v", sock, err) } client := httputil.NewClientConn(c, nil) defer client.Close() req, err := http.NewRequest(method, endpoint, nil) req.Header.Set("Content-Type", "application/json") if err != nil { return nil, fmt.Errorf("could not create new request: %v", err) } resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("could not perform request: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) return body, fmt.Errorf("received status != 200 OK: %s", resp.Status) } return ioutil.ReadAll(resp.Body) }
func TestByteView(t *testing.T) { for _, s := range []string{"", "x", "yy"} { for _, v := range []ByteView{of([]byte(s)), of(s)} { name := fmt.Sprintf("string %q, view %+v", s, v) if v.Len() != len(s) { t.Errorf("%s: Len = %d; want %d", name, v.Len(), len(s)) } if v.String() != s { t.Errorf("%s: String = %q; want %q", name, v.String(), s) } var longDest [3]byte if n := v.Copy(longDest[:]); n != len(s) { t.Errorf("%s: long Copy = %d; want %d", name, n, len(s)) } var shortDest [1]byte if n := v.Copy(shortDest[:]); n != min(len(s), 1) { t.Errorf("%s: short Copy = %d; want %d", name, n, min(len(s), 1)) } if got, err := ioutil.ReadAll(v.Reader()); err != nil || string(got) != s { t.Errorf("%s: Reader = %q, %v; want %q", name, got, err, s) } if got, err := ioutil.ReadAll(io.NewSectionReader(v, 0, int64(len(s)))); err != nil || string(got) != s { t.Errorf("%s: SectionReader of ReaderAt = %q, %v; want %q", name, got, err, s) } } } }
func ExecGenCmd(args []string) (string, error) { var cmd *exec.Cmd argsNew := make([]string, len(args)+1) argsNew[0] = "generate" for i, a := range args { argsNew[i+1] = a } cmd = exec.Command("./ocitools", argsNew...) cmd.Dir = "./plugins" // cmd.stdin = os.Stdin stderr, err := cmd.StderrPipe() if err != nil { log.Fatal("stderr err %v", err) } stdout, err := cmd.StdoutPipe() if err != nil { log.Fatalf("stdout err %v", err) } var retStr string err = cmd.Start() if err != nil { retb, _ := ioutil.ReadAll(stderr) retStr = string(retb) // stdoutReader.ReadRune() } else { retb, _ := ioutil.ReadAll(stdout) retStr = string(retb) } return retStr, err }
func TestHTTPconfig(t *testing.T) { lopts := nsqlookupd.NewOptions() lopts.Logger = test.NewTestLogger(t) _, _, lookupd1 := mustStartNSQLookupd(lopts) defer lookupd1.Exit() _, _, lookupd2 := mustStartNSQLookupd(lopts) defer lookupd2.Exit() opts := NewOptions() opts.Logger = test.NewTestLogger(t) _, httpAddr, nsqd := mustStartNSQD(opts) defer os.RemoveAll(opts.DataPath) defer nsqd.Exit() url := fmt.Sprintf("http://%s/config/nsqlookupd_tcp_addresses", httpAddr) resp, err := http.Get(url) test.Nil(t, err) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) test.Equal(t, 200, resp.StatusCode) test.Equal(t, "[]", string(body)) client := http.Client{} addrs := fmt.Sprintf(`["%s","%s"]`, lookupd1.RealTCPAddr().String(), lookupd2.RealTCPAddr().String()) url = fmt.Sprintf("http://%s/config/nsqlookupd_tcp_addresses", httpAddr) req, err := http.NewRequest("PUT", url, bytes.NewBuffer([]byte(addrs))) test.Nil(t, err) resp, err = client.Do(req) test.Nil(t, err) defer resp.Body.Close() body, _ = ioutil.ReadAll(resp.Body) test.Equal(t, 200, resp.StatusCode) test.Equal(t, addrs, string(body)) }