本文整理汇总了Golang中encoding/json.NewDecoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDecoder函数的具体用法?Golang NewDecoder怎么用?Golang NewDecoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDecoder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestParseFlavors
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: Handler
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: Do
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: poll
// 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: handleResponse
// 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: Me
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: TestAddNodeHandlerWithInvalidURLAddress
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: callRet
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: NewAccessToken
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: ExchangeAuthorizationForToken
// 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: ReadConfig
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: ParseJson
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: do
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: PostRead
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: loadSpec
// 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)
}