Golang NewDecoder示例

说明

golang newdecoder示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: encoding/json

示例#1
文件: flavor_test.go 项目: alvaropeon/hpcloud-kubesetup

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
}

示例#2
文件: prova.go 项目: GrupoEstudoMega/MegaRunning

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)
	}
}

示例#3
文件: client.go 项目: jkotrlik/salsaflow

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
}

示例#4
文件: client.go 项目: medigo/laika

// 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
}

示例#5
文件: jwt.go 项目: BitBalloon/bitballoon-cli

// 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
}

示例#6
文件: pushbullet.go 项目: raspberrypython/go-pushbullet

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
}

示例#7
文件: handlers_test.go 项目: mderaldo/tsuru

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\]`)
}

示例#8
文件: rpc.go 项目: JessonChan/go-sdk

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
}

示例#9
文件: google.go 项目: ecampbellrc/gdrive2slack

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
}

示例#10
文件: oauth.go 项目: dnsimple/strillone

// 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
}

示例#11
文件: slackcat.go 项目: pborreli/slackcat

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
}

示例#12
文件: event.go 项目: mingderwang/userstream

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
}

示例#13
文件: client.go 项目: yingkitw/gorouter

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
}

示例#14
文件: meddler.go 项目: RidleyLarsen/codegrinder

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
}

示例#15
文件: spec.go 项目: kimh/runc

// 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)
}

示例#16
文件: ndb.go 项目: abadojack/gondb

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)
}

示例#17
文件: pushbullet.go 项目: raspberrypython/go-pushbullet

// 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
}

示例#18
文件: statement.go 项目: emerald-ci/test-runner

// 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
}

示例#19
文件: outcomes_import_tool.go 项目: ryanmt/outcomes-import-tool

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
}

示例#20
文件: main.go 项目: yosida95/timetable

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
	}
}

示例#21
文件: hipchat.go 项目: wsdan/hipchat-go

// 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
}

示例#22
文件: config.go 项目: jcooklin/snap

// 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
}

示例#23
文件: twty.go 项目: mattn/twty

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)
}

示例#24
文件: file.go 项目: NioTeX/neat

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
}

示例#25
文件: linux.go 项目: spheromak/containerd

// 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)
}

示例#26
文件: docker_api_stats_test.go 项目: moxiegirl/docker

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))
}

示例#27
文件: main.go 项目: rajasec/ocitools

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
}

示例#28
文件: server.go 项目: iovisor/iomodules

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{}
}

示例#29
文件: json.go 项目: devick/flynn

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
}

示例#30
文件: logger_test.go 项目: osamingo/logrusow

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"])
}

展开阅读全文