func TestParseFlavors(t *testing.T) {

	flavorsTestFilePath := "./testdata/database_flavor_test_flavors.json"

	flavorsTestFile, err := os.Open("./testdata/database_flavor_test_flavors.json")
	if err != nil {
		t.Error(fmt.Errorf("Failed to open file %s: '%s'", flavorsTestFilePath, err.Error()))
	}

	flavorsContainer := FlavorsContainer{}
	err = json.NewDecoder(flavorsTestFile).Decode(&flavorsContainer)
	defer flavorsTestFile.Close()
	if err != nil {
		t.Error(fmt.Errorf("Failed to decode JSON file %s: '%s'", flavorsTestFilePath, err.Error()))
	}

	flavorTestFilePath := "./testdata/database_flavor_test_flavor.json"

	flavorTestFile, err := os.Open(flavorTestFilePath)
	if err != nil {
		t.Error(fmt.Errorf("Failed to open file %s: '%s'", flavorTestFilePath, err.Error()))
	}

	flavorContainer := FlavorContainer{}
	err = json.NewDecoder(flavorTestFile).Decode(&flavorContainer)
	defer flavorTestFile.Close()
	if err != nil {
		t.Error(fmt.Errorf("Failed to decode JSON file %s: '%s'", flavorTestFilePath, err.Error()))
	}

	return
}
Exemple #2
0
func Handler(response http.ResponseWriter, request *http.Request) {
	fmt.Println(request.Method)
	fmt.Println("Entrou no handler")
	fmt.Println(len(request.Cookies()))
	token, err := request.Cookie("token")
	fmt.Println(token.Value, err)
	data := url.Values{}
	data.Set("access_token", token.Value)
	//req = http.NewRequest("POST", "https://www.googleapis.com/oauth2/v1/tokeninfo", nil)
	resp, err := http.Post("https://www.googleapis.com/oauth2/v1/tokeninfo", "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode()))
	//req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param="+token)
	//http.
	var retorno ValidaToken
	json.NewDecoder(resp.Body).Decode(&retorno)
	fmt.Println(retorno.Error, retorno.Email)

	switch request.Method {
	case "GET":
		provas := Provas()
		fmt.Println(provas)
		js, _ := json.MarshalIndent(provas, " ", "   ")
		response.Write(js)

	case "POST":
		var prova Prova
		json.NewDecoder(request.Body).Decode(&prova)
		err := Insere(&prova)
		fmt.Println(err)
	}
}
Exemple #3
0
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) {
	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode > 299 {
		var errObject Error
		if err := json.NewDecoder(resp.Body).Decode(&errObject); err != nil {
			return resp, &ErrAPI{Response: resp}
		}

		return resp, &ErrAPI{
			Response: resp,
			Err:      &errObject,
		}
	}

	if v != nil {
		err = json.NewDecoder(resp.Body).Decode(v)
	}

	return resp, err
}
Exemple #4
0
// Poll polls the Laika API for the latest Feature statuses, storing the results
// in the internal cache.
func (c *client) poll() error {
	req, err := http.NewRequest("GET", c.url.String(), nil)
	if err != nil {
		return err
	}

	req.SetBasicAuth(c.username, c.password)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	defer res.Body.Close()

	if res.StatusCode < 200 || res.StatusCode >= 300 {
		e := new(Error)
		if err := json.NewDecoder(res.Body).Decode(e); err != nil {
			return err
		}

		return errors.New(e.Message)
	}

	features := []*Feature{}
	if err := json.NewDecoder(res.Body).Decode(&features); err != nil {
		return err
	}

	c.features.AddAll(features)

	return nil
}
Exemple #5
0
// handleResponse returns a filled in *oauth.Token given the *http.Response from
// a *http.Request created by buildRequest.
func handleResponse(r *http.Response) (*oauth.Token, error) {
	o := &oauth.Token{}
	defer r.Body.Close()
	if r.StatusCode != 200 {
		return o, errors.New("invalid response: " + r.Status)
	}
	b := &respBody{}
	err := json.NewDecoder(r.Body).Decode(b)
	if err != nil {
		return o, err
	}
	o.AccessToken = b.Access
	if b.IdToken != "" {
		// decode returned id token to get expiry
		o.AccessToken = b.IdToken
		s := strings.Split(b.IdToken, ".")
		if len(s) < 2 {
			return nil, errors.New("invalid token received")
		}
		d, err := base64Decode(s[1])
		if err != nil {
			return o, err
		}
		c := &ClaimSet{}
		err = json.NewDecoder(bytes.NewBuffer(d)).Decode(c)
		if err != nil {
			return o, err
		}
		o.Expiry = time.Unix(c.Exp, 0)
		return o, nil
	}
	o.Expiry = time.Now().Add(b.ExpiresIn * time.Second)
	return o, nil
}
func (c *Client) Me() (*User, error) {
	req := c.buildRequest("/users/me", nil)
	resp, err := c.Client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		var errjson errorResponse
		dec := json.NewDecoder(resp.Body)
		err = dec.Decode(&errjson)
		if err == nil {
			return nil, &errjson.ErrResponse
		}

		return nil, errors.New(resp.Status)
	}

	var userResponse User
	dec := json.NewDecoder(resp.Body)
	err = dec.Decode(&userResponse)
	if err != nil {
		return nil, err
	}
	return &userResponse, nil
}
Exemple #7
0
func (s *HandlersSuite) TestAddNodeHandlerWithInvalidURLAddress(c *check.C) {
	config.Set("docker:cluster:redis-server", "127.0.0.1:6379")
	defer config.Unset("docker:cluster:redis-server")
	b := bytes.NewBufferString(`{"address": "/invalid", "pool": "pool1"}`)
	req, err := http.NewRequest("POST", "/docker/node?register=true", b)
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	err = addNodeHandler(rec, req, nil)
	c.Assert(err, check.IsNil)
	var result map[string]string
	err = json.NewDecoder(rec.Body).Decode(&result)
	c.Assert(err, check.IsNil)
	c.Assert(rec.Code, check.Equals, http.StatusBadRequest)
	c.Assert(result["error"], check.Matches, "Invalid address url: host cannot be empty")
	b = bytes.NewBufferString(`{"address": "xxx://abc/invalid", "pool": "pool1"}`)
	req, err = http.NewRequest("POST", "/docker/node?register=true", b)
	c.Assert(err, check.IsNil)
	rec = httptest.NewRecorder()
	err = addNodeHandler(rec, req, nil)
	c.Assert(err, check.IsNil)
	err = json.NewDecoder(rec.Body).Decode(&result)
	c.Assert(err, check.IsNil)
	c.Assert(rec.Code, check.Equals, http.StatusBadRequest)
	c.Assert(result["error"], check.Matches, `Invalid address url: scheme must be http\[s\]`)
}
Exemple #8
0
func callRet(ret interface{}, resp *http.Response) (code int, err error) {
	defer resp.Body.Close()
	code = resp.StatusCode
	if code/100 == 2 {
		if ret != nil && resp.ContentLength != 0 {
			err = json.NewDecoder(resp.Body).Decode(ret)
			if err != nil {
				code = api.UnexceptedResponse
			}
		}
	} else {
		if resp.ContentLength != 0 {
			if ct, ok := resp.Header["Content-Type"]; ok && ct[0] == "application/json" {
				var ret1 ErrorRet
				json.NewDecoder(resp.Body).Decode(&ret1)
				if ret1.Error != "" {
					err = errors.New(ret1.Error)
					return
				}
			}
		}
		err = api.Errno(code)
	}
	return
}
Exemple #9
0
func NewAccessToken(conf *OauthConfiguration, client *http.Client, code string) (string, string, StatusCode, error) {
	response, err := client.PostForm("https://accounts.google.com/o/oauth2/token", url.Values{
		"code":          {code},
		"client_id":     {conf.ClientId},
		"client_secret": {conf.ClientSecret},
		"redirect_uri":  {conf.RedirectUri},
		"grant_type":    {"authorization_code"},
	})
	if err != nil {
		return "", "", CannotConnect, err
	}
	defer response.Body.Close()
	if response.StatusCode >= 400 {
		oauthError := &OauthError{}
		err = json.NewDecoder(response.Body).Decode(oauthError)
		if err != nil {
			return "", "", CannotDeserialize, err
		}
		if response.StatusCode >= 500 {
			return "", "", ServerError, errors.New(oauthError.ErrorDescription)
		}
		if response.StatusCode == 401 || response.StatusCode == 403 {
			return "", "", Unauthorized, errors.New(oauthError.ErrorDescription)
		}
		return "", "", ApiError, errors.New(oauthError.ErrorDescription)
	}
	var self = new(OauthState)
	err = json.NewDecoder(response.Body).Decode(self)
	if err != nil {
		return "", "", CannotDeserialize, err
	}
	return self.RefreshToken, self.AccessToken, Ok, nil
}
Exemple #10
0
// ExchangeAuthorizationForToken exchanges the short-lived authorization code for an access token
// you can use to authenticate your API calls.
func (s *OauthService) ExchangeAuthorizationForToken(authorization *ExchangeAuthorizationRequest) (*AccessToken, error) {
	path := versioned("/oauth/access_token")

	req, err := s.client.NewRequest("POST", path, authorization)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.HttpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		errorResponse := &ExchangeAuthorizationError{}
		errorResponse.HttpResponse = resp
		json.NewDecoder(resp.Body).Decode(errorResponse)
		return nil, errorResponse
	}

	accessToken := &AccessToken{}
	err = json.NewDecoder(resp.Body).Decode(accessToken)

	return accessToken, err
}
Exemple #11
0
func ReadConfig() (*Config, error) {
	homeDir := ""
	usr, err := user.Current()
	if err == nil {
		homeDir = usr.HomeDir
	}

	for _, path := range []string{"/etc/slackcat.conf", homeDir + "/.slackcat.conf", "./slackcat.conf"} {
		file, err := os.Open(path)
		if os.IsNotExist(err) {
			continue
		}
		if err != nil {
			return nil, err
		}

		json.NewDecoder(file)
		conf := Config{}
		err = json.NewDecoder(file).Decode(&conf)
		if err != nil {
			return nil, err
		}
		return &conf, nil
	}
	return &Config{}, nil
}
Exemple #12
0
func ParseJson(jsonText string) interface{} {
	hash := map[string]string{}
	decoder := json.NewDecoder(strings.NewReader(jsonText))
	decoder.Decode(&hash)

	decoder = json.NewDecoder(strings.NewReader(jsonText))
	if _, hasKey := hash["friends"]; hasKey {
		friendList := FriendList{}
		decoder.Decode(&friendList)
		return &friendList
	} else if _, hasKey := hash["event"]; hasKey {
		return parseEvent(decoder, hash["event"])
	} else if _, hasKey := hash["delete"]; hasKey {
		deleteHash := map[string]map[string]*Delete{}
		decoder.Decode(&deleteHash)
		return deleteHash["delete"]["status"]
	} else if _, hasKey := hash["created_at"]; hasKey {
		tweet := twitter.Tweet{}
		decoder.Decode(&tweet)
		return &tweet
	} else if _, hasKey := hash["direct_message"]; hasKey {
		dm := Record{}
		decoder := json.NewDecoder(strings.NewReader(jsonText))
		decoder.Decode(&dm)
		//spew.Dump(dm)
		return &dm
	}
	return nil
}
Exemple #13
0
func (c *client) do(req *http.Request, response interface{}) error {
	trace.DumpRequest(req)

	res, err := c.httpClient.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	trace.DumpResponse(res)

	if res.StatusCode == http.StatusUnauthorized {
		return Error{Type: "unauthorized", Message: "unauthorized"}
	}

	if res.StatusCode > 299 {
		errResponse := Error{}
		json.NewDecoder(res.Body).Decode(&errResponse)
		return errResponse
	}

	if response != nil {
		return json.NewDecoder(res.Body).Decode(response)
	}

	return nil
}
Exemple #14
0
func (zip JSONMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
	ptr := scanTarget.(*[]byte)
	if ptr == nil {
		return fmt.Errorf("JSONMeddler.PostRead: nil pointer")
	}
	raw := *ptr

	if zip {
		// un-gzip and decode json
		gzipReader, err := gzip.NewReader(bytes.NewReader(raw))
		if err != nil {
			return fmt.Errorf("Error creating gzip Reader: %v", err)
		}
		defer gzipReader.Close()
		jsonDecoder := json.NewDecoder(gzipReader)
		if err := jsonDecoder.Decode(fieldAddr); err != nil {
			return fmt.Errorf("JSON decoder/gzip error: %v", err)
		}
		if err := gzipReader.Close(); err != nil {
			return fmt.Errorf("Closing gzip reader: %v", err)
		}

		return nil
	}

	// decode json
	jsonDecoder := json.NewDecoder(bytes.NewReader(raw))
	if err := jsonDecoder.Decode(fieldAddr); err != nil {
		return fmt.Errorf("JSON decode error: %v", err)
	}

	return nil
}
Exemple #15
0
// loadSpec loads the specification from the provided path.
// If the path is empty then the default path will be "config.json"
func loadSpec(cPath, rPath string) (spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, err error) {
	cf, err := os.Open(cPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("JSON specification file %s not found", cPath)
		}
		return spec, rspec, err
	}
	defer cf.Close()

	rf, err := os.Open(rPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("JSON runtime config file %s not found", rPath)
		}
		return spec, rspec, err
	}
	defer rf.Close()

	if err = json.NewDecoder(cf).Decode(&spec); err != nil {
		return spec, rspec, err
	}
	if err = json.NewDecoder(rf).Decode(&rspec); err != nil {
		return spec, rspec, err
	}
	return spec, rspec, validateSpec(spec, rspec)
}
Exemple #16
0
func (c *Client) apiGet(endpoint string, form url.Values, data interface{}) error {
	if form == nil {
		form = url.Values{}
	}

	form.Set("api_key", c.APIKey)
	form.Set("format", "json")

	urlStr := BaseURL + endpoint + form.Encode()

	req, err := http.NewRequest("GET", urlStr, nil)
	if err != nil {
		return err
	}

	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		var apiError map[string]APIError
		json.NewDecoder(resp.Body).Decode(&apiError) //This ain't cool.
		return apiError["error"]
	}

	defer resp.Body.Close()

	return json.NewDecoder(resp.Body).Decode(data)
}
// Devices fetches a list of devices from PushBullet.
func (c *Client) Devices() ([]*Device, error) {
	req := c.buildRequest("/devices", nil)
	resp, err := c.Client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		var errjson errorResponse
		dec := json.NewDecoder(resp.Body)
		err = dec.Decode(&errjson)
		if err == nil {
			return nil, &errjson.ErrResponse
		}

		return nil, errors.New(resp.Status)
	}

	var devResp deviceResponse
	dec := json.NewDecoder(resp.Body)
	err = dec.Decode(&devResp)
	if err != nil {
		return nil, err
	}

	devices := append(devResp.Devices, devResp.SharedDevices...)
	return devices, nil
}
Exemple #18
0
// CreateStatements creates and signs a statement from a stream of grants
// and revocations in a JSON array.
func CreateStatement(grants, revocations io.Reader, expiration time.Duration, key libtrust.PrivateKey, chain []*x509.Certificate) (*Statement, error) {
	var statement Statement
	err := json.NewDecoder(grants).Decode(&statement.jsonStatement.Grants)
	if err != nil {
		return nil, err
	}
	err = json.NewDecoder(revocations).Decode(&statement.jsonStatement.Revocations)
	if err != nil {
		return nil, err
	}
	statement.jsonStatement.Expiration = time.Now().UTC().Add(expiration)
	statement.jsonStatement.IssuedAt = time.Now().UTC()

	b, err := json.MarshalIndent(&statement.jsonStatement, "", "   ")
	if err != nil {
		return nil, err
	}

	statement.signature, err = libtrust.NewJSONSignature(b)
	if err != nil {
		return nil, err
	}
	err = statement.signature.SignWithChain(key, chain)
	if err != nil {
		return nil, err
	}

	return &statement, nil
}
func getAvailable(req request) []importableGuid {
	req.Body = ""
	req.Method = "GET"
	req.Endpoint = "/api/v1/global/outcomes_import/available"

	client, hreq := httpRequest(req)
	log.Printf("Requesting available guids from %s", hreq.URL)
	resp, err := client.Do(hreq)
	if err != nil {
		log.Fatalln(err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	var errs apiErrors
	if json.NewDecoder(bytes.NewReader(body)).Decode(&errs); len(errs.Errors) > 0 {
		printErrors(errs.Errors)
		os.Exit(1)
	}

	var guids []importableGuid
	if e := json.NewDecoder(bytes.NewReader(body)).Decode(&guids); e != nil {
		log.Fatalln("JSON decoding error.  Make sure your API key is correct and that you have permission to read global outcomes", e)
	}
	return guids
}
Exemple #20
0
func main() {
	var decoder *json.Decoder
	if fname == "" {
		decoder = json.NewDecoder(os.Stdin)
	} else {
		fh, err := os.OpenFile(fname, os.O_RDONLY, 0)
		if err != nil {
			log.Fatal(err)
		}
		defer fh.Close()

		decoder = json.NewDecoder(fh)
	}

	query := make(Query, 0)
	err := decoder.Decode(&query)
	if err != nil {
		log.Fatal(err)
	}
	filter := query.Filter()

	prog, err := agqr.BuildTimetable()
	if err != nil {
		log.Fatal(err)
	}

	for prog != nil {
		if filter.Match(prog) {
			fmt.Println(prog.Cron(cronTmpl))
		}

		prog = prog.Next
	}
}
Exemple #21
0
// Do performs the request, the json received in the response is decoded
// and stored in the value pointed by v.
// Do can be used to perform the request created with NewRequest, as the latter
// it should be used only for API requests not implemented in this library.
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) {

	resp, err := urlfetch.Client(c.ctx).Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if AuthTest {
		// If AuthTest is enabled, the reponse won't be the
		// one defined in the API endpoint.
		err = json.NewDecoder(resp.Body).Decode(&AuthTestResponse)
	} else {
		if c := resp.StatusCode; c < 200 || c > 299 {
			return resp, fmt.Errorf("Server returns status %d", c)
		}

		if v != nil {
			if w, ok := v.(io.Writer); ok {
				io.Copy(w, resp.Body)
			} else {
				err = json.NewDecoder(resp.Body).Decode(v)
			}
		}
	}
	return resp, err
}
Exemple #22
0
// UnmarshalJSON unmarshals valid json into pluginConfig.  An example Config
// github.com/intelsdi-x/snap/blob/master/examples/configs/snap-config-sample.json
func (p *pluginConfig) UnmarshalJSON(data []byte) error {
	t := map[string]interface{}{}
	dec := json.NewDecoder(bytes.NewReader(data))
	dec.UseNumber()
	if err := dec.Decode(&t); err != nil {
		return err
	}

	//process the key value pairs for ALL plugins
	if v, ok := t["all"]; ok {
		jv, err := json.Marshal(v)
		if err != nil {
			return err
		}
		cdn := &cdata.ConfigDataNode{}
		dec = json.NewDecoder(bytes.NewReader(jv))
		dec.UseNumber()
		if err := dec.Decode(&cdn); err != nil {
			return err
		}
		p.All = cdn
	}

	//process the hierarchy of plugins
	for _, typ := range []string{"collector", "processor", "publisher"} {
		if err := unmarshalPluginConfig(typ, p, t); err != nil {
			return err
		}
	}

	return nil
}
Exemple #23
0
func rawCall(token *oauth.Credentials, method string, uri string, opt map[string]string, res interface{}) error {
	param := make(url.Values)
	for k, v := range opt {
		param.Set(k, v)
	}
	oauthClient.SignParam(token, method, uri, param)
	var resp *http.Response
	var err error
	if method == "GET" {
		uri = uri + "?" + param.Encode()
		resp, err = http.Get(uri)
	} else {
		resp, err = http.PostForm(uri, url.Values(param))
	}
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if res == nil {
		return nil
	}
	if *debug {
		return json.NewDecoder(io.TeeReader(resp.Body, os.Stdout)).Decode(&res)
	}
	return json.NewDecoder(resp.Body).Decode(&res)
}
Exemple #24
0
func (a *File) Restore(ctx neat.Context) error {

	// Restore the settings
	name := a.makePath("config")
	f, err := os.Open(name)
	if err != nil {
		return err
	}
	d := json.NewDecoder(f)
	if err = d.Decode(&ctx); err != nil {
		f.Close()
		return err
	}
	f.Close()

	// Restore the state values
	for k, v := range ctx.State() {
		name := a.makePath(k)
		if _, err := os.Stat(name); os.IsNotExist(err) {
			continue
		}

		f, err = os.Open(name)
		if err != nil {
			return err
		}
		d = json.NewDecoder(f)
		if err = d.Decode(&v); err != nil {
			f.Close()
			return err
		}
		f.Close()
	}
	return nil
}
Exemple #25
0
// loadSpec loads the specification from the provided path.
// If the path is empty then the default path will be "config.json"
func (r *libcontainerRuntime) loadSpec(cPath, rPath string) (spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, err error) {
	cf, err := os.Open(cPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("JSON specification file at %s not found", cPath)
		}
		return spec, rspec, err
	}
	defer cf.Close()

	rf, err := os.Open(rPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("JSON runtime config file at %s not found", rPath)
		}
		return spec, rspec, err
	}
	defer rf.Close()

	if err = json.NewDecoder(cf).Decode(&spec); err != nil {
		return spec, rspec, fmt.Errorf("unmarshal %s: %v", cPath, err)
	}
	if err = json.NewDecoder(rf).Decode(&rspec); err != nil {
		return spec, rspec, fmt.Errorf("unmarshal %s: %v", rPath, err)
	}
	return spec, rspec, r.checkSpecVersion(spec)
}
func (s *DockerSuite) TestApiStatsContainerGetMemoryLimit(c *check.C) {
	testRequires(c, DaemonIsLinux)

	resp, body, err := sockRequestRaw("GET", "/info", nil, "application/json")
	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
	var info types.Info
	err = json.NewDecoder(body).Decode(&info)
	c.Assert(err, checker.IsNil)
	body.Close()

	// don't set a memory limit, the memory limit should be system memory
	conName := "foo"
	dockerCmd(c, "run", "-d", "--name", conName, "busybox", "top")
	c.Assert(waitRun(conName), checker.IsNil)

	resp, body, err = sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", conName), nil, "")
	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, http.StatusOK)
	c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json")

	var v *types.Stats
	err = json.NewDecoder(body).Decode(&v)
	c.Assert(err, checker.IsNil)
	body.Close()
	c.Assert(fmt.Sprintf("%d", v.MemoryStats.Limit), checker.Equals, fmt.Sprintf("%d", info.MemTotal))
}
Exemple #27
0
func loadSpecConfig() (spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, err error) {
	cPath := "config.json"
	cf, err := os.Open(cPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("config.json not found")
		}
	}
	defer cf.Close()

	rPath := "runtime.json"
	rf, err := os.Open(rPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("runtime.json not found")
		}
	}
	defer rf.Close()

	if err = json.NewDecoder(cf).Decode(&spec); err != nil {
		return
	}
	if err = json.NewDecoder(rf).Decode(&rspec); err != nil {
		return
	}
	return spec, rspec, nil
}
Exemple #28
0
func (g *GbpServer) handlePolicyPost(r *http.Request) routeResponse {
	var req createPolicyRequestUri
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		panic(err)
	}

	/* Received URI to fetch policy for relevant endpoints to this Agent */
	reqUri := req.Uri
	if reqUriRegex.MatchString(reqUri) == false {
		panic(fmt.Errorf("Uri returned: %s is not in format `^/restconf/operational/resolved-policy:resolved-policies/resolved-policy/<string>/<string>/<string>/<string>/`", reqUri))
	}

	/* Authenticate */
	Debug.Printf(g.upstreamUri + reqUri)
	reqGet, err := http.NewRequest("GET", g.upstreamUri+reqUri, nil)
	reqGet.SetBasicAuth("admin", "admin")

	client := http.Client{}
	resp, err := client.Do(reqGet)
	if err != nil {
		Error.Printf("Error : %s", err)
	}
	var req2 ResolvedPolicy

	if err := json.NewDecoder(resp.Body).Decode(&req2); err != nil {
		panic(err)
	}

	for _, policy := range req2.ResolvedPolicies {
		if err := g.dataplane.ParsePolicy(policy); err != nil {
			panic(err)
		}
	}
	return routeResponse{}
}
Exemple #29
0
func (c *Client) rawReq(method, rawurl string, header http.Header, in, out interface{}) (*http.Response, error) {
	req, err := c.prepareReq(method, rawurl, header, in)
	if err != nil {
		return nil, err
	}
	res, err := c.HTTP.Do(req)
	if err != nil {
		return nil, err
	}
	if res.StatusCode != 200 {
		defer res.Body.Close()
		if strings.Contains(res.Header.Get("Content-Type"), "application/json") {
			var jsonErr httphelper.JSONError
			if err := json.NewDecoder(res.Body).Decode(&jsonErr); err == nil {
				return res, jsonErr
			}
		}
		if res.StatusCode == 404 {
			return res, c.ErrNotFound
		}
		return res, &url.Error{
			Op:  req.Method,
			URL: req.URL.String(),
			Err: fmt.Errorf("httpclient: raw req: unexpected status %d", res.StatusCode),
		}
	}
	if out != nil {
		defer res.Body.Close()
		return res, json.NewDecoder(res.Body).Decode(out)
	}
	return res, nil
}
Exemple #30
0
func TestDebug(t *testing.T) {

	// only message

	dummy.Reset()

	msg := "debug test message"
	Debug(msg)
	time.Sleep(time.Millisecond)

	m := map[string]interface{}{}
	assert.NoError(t, json.NewDecoder(dummy).Decode(&m))

	assert.Equal(t, msg, m["msg"])
	assert.Equal(t, logrus.DebugLevel.String(), m["level"])
	assert.Nil(t, m["id"])

	// with fields

	dummy.Reset()

	id := "vytxeTZskVKR7C7WgdSP3d"
	Debug(msg, logrus.Fields{"id": id})
	time.Sleep(time.Millisecond)

	m = map[string]interface{}{}
	assert.NoError(t, json.NewDecoder(dummy).Decode(&m))

	assert.Equal(t, msg, m["msg"])
	assert.Equal(t, logrus.DebugLevel.String(), m["level"])
	assert.Equal(t, id, m["id"])
}