本文整理汇总了Golang中encoding/json.NewDecoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDecoder函数的具体用法?Golang NewDecoder怎么用?Golang NewDecoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDecoder函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:alvaropeon,项目名称:hpcloud-kubesetup,代码行数:32,代码来源:flavor_test.go
示例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)
}
}
开发者ID:GrupoEstudoMega,项目名称:MegaRunning,代码行数:30,代码来源:prova.go
示例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
}
开发者ID:jkotrlik,项目名称:salsaflow,代码行数:26,代码来源:client.go
示例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
}
开发者ID:medigo,项目名称:laika,代码行数:36,代码来源:client.go
示例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
}
开发者ID:BitBalloon,项目名称:bitballoon-cli,代码行数:36,代码来源:jwt.go
示例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
}
开发者ID:raspberrypython,项目名称:go-pushbullet,代码行数:26,代码来源:pushbullet.go
示例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\]`)
}
开发者ID:mderaldo,项目名称:tsuru,代码行数:25,代码来源:handlers_test.go
示例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
}
开发者ID:JessonChan,项目名称:go-sdk,代码行数:25,代码来源:rpc.go
示例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
}
开发者ID:ecampbellrc,项目名称:gdrive2slack,代码行数:33,代码来源:google.go
示例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
}
开发者ID:dnsimple,项目名称:strillone,代码行数:28,代码来源:oauth.go
示例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
}
开发者ID:pborreli,项目名称:slackcat,代码行数:26,代码来源:slackcat.go
示例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
}
开发者ID:mingderwang,项目名称:userstream,代码行数:29,代码来源:event.go
示例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
}
开发者ID:yingkitw,项目名称:gorouter,代码行数:27,代码来源:client.go
示例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
}
开发者ID:RidleyLarsen,项目名称:codegrinder,代码行数:33,代码来源:meddler.go
示例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)
}
开发者ID:kimh,项目名称:runc,代码行数:29,代码来源:spec.go
示例16: apiGet
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)
}
开发者ID:abadojack,项目名称:gondb,代码行数:30,代码来源:ndb.go
示例17: Devices
// 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
}
开发者ID:raspberrypython,项目名称:go-pushbullet,代码行数:29,代码来源:pushbullet.go
示例18: CreateStatement
// 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
}
开发者ID:emerald-ci,项目名称:test-runner,代码行数:31,代码来源:statement.go
示例19: getAvailable
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
}
开发者ID:ryanmt,项目名称:outcomes-import-tool,代码行数:26,代码来源:outcomes_import_tool.go
示例20: main
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
}
}
开发者ID:yosida95,项目名称:timetable,代码行数:34,代码来源:main.go
注:本文中的encoding/json.NewDecoder函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论