本文整理汇总了Golang中json.NewDecoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDecoder函数的具体用法?Golang NewDecoder怎么用?Golang NewDecoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDecoder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: LoadJsonPermission
func LoadJsonPermission(userReader io.Reader, groupReader io.Reader) (jPermission *JsonPermission, err os.Error) {
// Load users
usersDecoder := json.NewDecoder(userReader)
var users Users
if err = usersDecoder.Decode(&users); err != nil {
return
}
// Load groups
groupsDecoder := json.NewDecoder(groupReader)
var groups Groups
if err = groupsDecoder.Decode(&groups); err != nil {
return nil, err
}
jPermission = &JsonPermission{
users: make(map[string]*CachedUser),
}
// Cache users and merge groups into users.
for name, user := range users {
permissions := make([]string, len(user.Permissions))
for i := range user.Permissions {
permissions[i] = user.Permissions[i]
}
inhPerm := getInheritance(user.Groups, groups)
for _, perm := range inhPerm {
permissions = append(permissions, perm)
}
jPermission.users[name] = &CachedUser{permissions: permissions}
}
// Cache default user.
defaultUser := &CachedUser{
permissions: make([]string, 0),
}
for _, group := range groups {
if group.Default {
for _, perm := range group.Permissions {
defaultUser.permissions = append(defaultUser.permissions, perm)
}
inhPerm := getInheritance(group.Inheritance, groups)
for _, perm := range inhPerm {
defaultUser.permissions = append(defaultUser.permissions, perm)
}
}
}
jPermission.defaultUser = defaultUser
return jPermission, nil
}
示例2: deserialize
// deserialize decodes a value using json.
func deserialize(src []byte, dst interface{}) error {
dec := json.NewDecoder(bytes.NewBuffer(src))
if err := dec.Decode(dst); err != nil {
return err
}
return nil
}
示例3: retrieveInfo
func retrieveInfo(client oauth2_client.OAuth2Client, apiUrl, id string, m url.Values, value interface{}) (err os.Error) {
uri := TWITTER_API_ENDPOINT
for _, s := range []string{apiUrl, id} {
if len(s) > 0 {
if uri[len(uri)-1] != '/' {
uri += "/"
}
uri += s
}
}
headers := make(http.Header)
headers.Set("Accept", "application/json")
if m == nil {
m = make(url.Values)
}
resp, _, err := oauth2_client.AuthorizedGetRequest(client, headers, uri, m)
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode >= 400 {
var e ErrorResponse
b, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(b, &e)
if len(e.Error) > 0 {
err = os.NewError(e.Error)
} else {
err = os.NewError(string(b))
}
} else {
err = json.NewDecoder(resp.Body).Decode(value)
}
}
return err
}
示例4: StaticSet
// StaticSet returns the whole of the static set members of that directory
func (dr *DirReader) StaticSet() ([]*blobref.BlobRef, os.Error) {
if dr.staticSet != nil {
return dr.staticSet, nil
}
staticSetBlobref := blobref.Parse(dr.ss.Entries)
if staticSetBlobref == nil {
return nil, fmt.Errorf("schema/filereader: Invalid blobref\n")
}
rsc, _, err := dr.fetcher.Fetch(staticSetBlobref)
if err != nil {
return nil, fmt.Errorf("schema/filereader: fetching schema blob %s: %v", staticSetBlobref, err)
}
ss := new(Superset)
if err = json.NewDecoder(rsc).Decode(ss); err != nil {
return nil, fmt.Errorf("schema/filereader: decoding schema blob %s: %v", staticSetBlobref, err)
}
if ss.Type != "static-set" {
return nil, fmt.Errorf("schema/filereader: expected \"static-set\" schema blob for %s, got %q", staticSetBlobref, ss.Type)
}
for _, s := range ss.Members {
member := blobref.Parse(s)
if member == nil {
return nil, fmt.Errorf("schema/filereader: invalid (static-set member) blobref\n")
}
dr.staticSet = append(dr.staticSet, member)
}
return dr.staticSet, nil
}
示例5: configure
func configure(flags ServerConfig) {
if flag.NArg() == 1 {
fname := flag.Arg(0)
f, err := os.Open(fname)
if err != nil {
log.Fatalf("Config reading error: %s\n", err.String())
}
dec := json.NewDecoder(f)
err = dec.Decode(&server)
if err != nil {
log.Fatalf("Config parsing error: %s\n", err.String())
}
action = "serve"
}
flag.Visit(func(flag *flag.Flag) {
switch flag.Name {
case "version":
action = "version"
case "port":
server.Port = flags.Port
case "host":
server.Host = flags.Host
case "tls-cert":
server.TLSCertFile = flags.TLSCertFile
case "tls-key":
server.TLSKeyFile = flags.TLSKeyFile
case "log":
server.Log = flags.Log
}
})
}
示例6: loadProfile
func (self *target) loadProfile(packageName string) os.Error {
file, err := os.Open(packageName + ".gofiles")
if err != nil {
return err
}
defer file.Close()
var prof Profile
if err := json.NewDecoder(file).Decode(&prof); err != nil {
return err
}
if packageName != "main" {
self.targetName = prof.Target
}
for _, entry := range prof.GoFiles {
// TODO parse wildcard and ~
if _, exist := self.files[entry]; exist {
continue
}
if src, err := self.ctx.getSource(entry); err != nil {
return err
} else if src != nil && src.packageName == packageName {
self.files[src.filepath] = src
}
}
return nil
}
示例7: TestServer
func TestServer(t *testing.T) {
type addResp struct {
Id interface{} "id"
Result Reply "result"
Error string "error"
}
cli, srv := net.Pipe()
defer cli.Close()
go ServeConn(srv)
dec := json.NewDecoder(cli)
// Send hand-coded requests to server, parse responses.
for i := 0; i < 10; i++ {
fmt.Fprintf(cli, `{"method": "Arith.Add", "id": "\u%04d", "params": [{"A": %d, "B": %d}]}`, i, i, i+1)
var resp addResp
err := dec.Decode(&resp)
if err != nil {
t.Fatalf("Decode: %s", err)
}
if resp.Error != "" {
t.Fatalf("resp.Error: %s", resp.Error)
}
if resp.Id.(string) != string(i) {
t.Fatalf("resp: bad id %q want %q", resp.Id.(string), string(i))
}
if resp.Result.C != 2*i+1 {
t.Fatalf("resp: bad result: %d+%d=%d", i, i+1, resp.Result.C)
}
}
}
示例8: handleCreateGroup
func (p *MockGoogleClient) handleCreateGroup(req *http.Request) (resp *http.Response, err os.Error) {
//fmt.Printf("calling handleCreateGroup\n")
b := NewGroupResponse()
err = json.NewDecoder(req.Body).Decode(b)
if err != nil {
panic(fmt.Sprintf("Error creating group: %s\n", err.String()))
resp, _ = createJSONHttpResponseFromObj(req, NewGroupResponse())
resp.Status = "500 INTERNAL SERVER ERROR"
resp.StatusCode = http.StatusInternalServerError
return
}
if b.Entry == nil {
resp, err = createJSONHttpResponseFromObj(req, NewGroupResponse())
resp.Status = "400 BAD REQUEST"
resp.StatusCode = http.StatusBadRequest
return
}
e := b.Entry
groupId := p.generateId()
e.Id.Value = groupId
e.Etag = p.generateEtag()
e.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT)
p.groupsById[groupId] = e
r := NewGroupResponse()
r.Entry = e
r.Entry.Xmlns = XMLNS_ATOM
r.Entry.XmlnsGcontact = XMLNS_GCONTACT
r.Entry.XmlnsBatch = XMLNS_GDATA_BATCH
r.Entry.XmlnsGd = XMLNS_GD
//fmt.Printf("Contact Entry: %v\n", c.Name)
return createJSONHttpResponseFromObj(req, r)
}
示例9: home
// home handles requests to the home page.
func home(req *web.Request) {
token, err := credentials(req, "tok")
if err != nil {
homeLoggedOut(req)
return
}
param := make(web.Values)
url := "http://api.twitter.com/1/statuses/home_timeline.json"
oauthClient.SignParam(token, "GET", url, param)
url = url + "?" + param.FormEncodedString()
resp, err := http.Get(url)
if err != nil {
req.Error(web.StatusInternalServerError, err)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
req.Error(web.StatusInternalServerError, os.NewError(fmt.Sprint("Status ", resp.StatusCode)))
return
}
var d interface{}
err = json.NewDecoder(resp.Body).Decode(&d)
if err != nil {
req.Error(web.StatusInternalServerError, err)
return
}
homeTempl.Execute(req.Respond(web.StatusOK, web.HeaderContentType, web.ContentTypeHTML), d)
}
示例10: LoadBlockDefs
func LoadBlockDefs(reader io.Reader) (blocks BlockTypeList, err os.Error) {
blocksStr := make(map[string]blockDef)
decoder := json.NewDecoder(reader)
err = decoder.Decode(&blocksStr)
// Find the max block ID so we allocate the correct amount of memory. Also
// range check the IDs.
maxId := 0
for idStr := range blocksStr {
var id int
id, err = strconv.Atoi(idStr)
if err != nil {
return
}
if id < BlockIdMin || id > BlockIdMax {
err = os.NewError(fmt.Sprintf(
"Encountered block type with ID %d which is outside the range"+
"%d <= N <= %d", id, BlockIdMin, BlockIdMax))
return
}
if id > maxId {
maxId = id
}
}
// Convert map string keys to ints.
blocks = make(BlockTypeList, maxId+1)
for idStr, blockDef := range blocksStr {
var id int
id, _ = strconv.Atoi(idStr)
if blocks[id].defined {
err = os.NewError(fmt.Sprintf(
"Block ID %d defined more than once.", id))
}
var block *BlockType
block, err = blockDef.LoadBlockType()
if err != nil {
return
}
block.id = BlockId(id)
block.defined = true
blocks[id] = *block
}
// Put VoidAspect in any undefined blocks rather than leave it nil, and also
// set id on each block type.
for id := range blocks {
block := &blocks[id]
block.id = BlockId(id)
if !block.defined {
void := makeVoidAspect()
block.Aspect = void
void.setAttrs(&block.BlockAttrs)
}
}
return
}
示例11: Start
func (this *JSONInterface) Start() {
for {
d := json.NewDecoder(this.Conn)
req := NewJSONRequest()
err := d.Decode(req)
if err != nil {
fmt.Printf("%s\n", err)
break
}
switch req.Action {
case "stream":
fmt.Printf("It's a stream request\n")
port := int32(req.Parameters["port"].(float64))
nodeid_string := req.Parameters["nodeid"].(string)
nodeid := make([]byte, 20)
_, err := fmt.Sscanf(nodeid_string, "%x", &nodeid)
if err != nil {
fmt.Printf("%s\n", err)
break
}
fmt.Printf("nodeid: %x\n", nodeid)
this.PipeStream(nodeid, port)
case "store":
}
}
}
示例12: parseConfig
func parseConfig() {
configPath := ConfigFilePath()
f, err := os.Open(configPath)
switch {
case err != nil && err.(*os.PathError).Error.(os.Errno) == syscall.ENOENT:
// TODO: write empty file?
return
case err != nil:
log.Printf("Error opening config file %q: %v", ConfigFilePath(), err)
return
}
defer f.Close()
dj := json.NewDecoder(f)
if err := dj.Decode(&config); err != nil {
extra := ""
if serr, ok := err.(*json.SyntaxError); ok {
if _, serr := f.Seek(0, os.SEEK_SET); serr != nil {
log.Fatalf("seek error: %v", serr)
}
line, col, highlight := errorutil.HighlightBytePosition(f, serr.Offset)
extra = fmt.Sprintf(":\nError at line %d, column %d (file offset %d):\n%s",
line, col, serr.Offset, highlight)
}
log.Fatalf("error parsing JSON object in config file %s%s\n%v",
ConfigFilePath(), extra, err)
}
if err := jsonconfig.EvaluateExpressions(config); err != nil {
log.Fatalf("error expanding JSON config expressions in %s: %v", configPath, err)
}
}
示例13: LoadDatabase
func LoadDatabase(dir string) Database {
d := make([]*Motif, 0)
dirHandle, ok := os.Open(dir)
if ok != nil {
panic("database failure" + ok.String())
}
dbnames, _ := dirHandle.Readdirnames(0)
LOAD:
for _, fname := range dbnames {
if !strings.HasSuffix(fname, ".zellij") {
continue
}
entry, _ := os.Open(path.Join(dir, fname))
data := make([]*quadratic.Map, 2)
data[0], data[1] = quadratic.NewMap(), quadratic.NewMap()
json.NewDecoder(entry).Decode(&data)
for _, m := range d {
if m.Frame.Isomorphic(data[0]) {
m.Variations = append(m.Variations, data[1])
continue LOAD
}
}
d = append(d, &Motif{fname, data[0], []*quadratic.Map{data[1]}, nil})
}
fmt.Fprintf(os.Stderr, "Loaded database with %v frames\n", len(d))
return d
}
示例14: OutputTo
func (p *JSONMediaTypeInputHandler) OutputTo(req wm.Request, cxt wm.Context, writer io.Writer) (int, http.Header, os.Error) {
defer func() {
if p.reader != nil {
if closer, ok := p.reader.(io.Closer); ok {
closer.Close()
}
}
}()
//log.Printf("[JSONMTIH]: Calling OutputTo with reader %v\n", p.reader)
if p.reader == nil {
return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, nil)
}
obj := jsonhelper.NewJSONObject()
dec := json.NewDecoder(p.reader)
err := dec.Decode(&obj)
if err != nil {
headers := make(http.Header)
//headers.Set("Content-Type", wm.MIME_TYPE_JSON)
m := jsonhelper.NewJSONObject()
w := json.NewEncoder(writer)
m.Set("status", "error")
m.Set("message", err.String())
m.Set("result", nil)
w.Encode(m)
return 500, headers, err
}
return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, obj)
}
示例15: Get
func (user *TwUser) Get(r io.Reader) os.Error {
dec := json.NewDecoder(r)
if err := dec.Decode(user); err != nil {
return err
}
return nil
}