• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang json.Decoder类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中encoding/json.Decoder的典型用法代码示例。如果您正苦于以下问题:Golang Decoder类的具体用法?Golang Decoder怎么用?Golang Decoder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Decoder类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Telegram

// Telegram webhook
func Telegram(
	context appengine.Context, decoder *json.Decoder, token string) string {
	if token != teleToken {
		return "!OK"
	}
	var teleEvent telePayload
	decoder.Decode(&teleEvent)
	message := teleEvent.Message
	if strings.Index(message.Text, "/getcode") > -1 {
		code := GetAlphaNumberic(6)
		teleVerify := teleVerify{
			ChatId: message.Chat.Id,
			Code:   code,
			Date:   time.Now(),
			Name:   message.Chat.First_name,
		}
		if message.Chat.Id < 0 {
			teleVerify.Name = message.Chat.Title
		}
		key := datastore.NewIncompleteKey(
			context, "teleVerify", teleVerifyKey(context, code))
		datastore.Put(context, key, &teleVerify)
		SendTeleMessage(context, code, message.Chat.Id)
	} else if strings.Index(message.Text, "/start") > -1 {
		SendTeleMessage(
			context, "Welcome! Next step is to get registered with webhook.co",
			message.Chat.Id)
	} else if strings.Index(message.Text, "/help") > -1 {
		SendTeleMessage(
			context, "Get registered with webhook.co", message.Chat.Id)
	}
	return "OK"
}
开发者ID:PredictionGuru,项目名称:webhook,代码行数:34,代码来源:telegram.go


示例2: Load

func (app *AppPlugin) Load(decoder *json.Decoder, pluginDir string) error {
	if err := decoder.Decode(&app); err != nil {
		return err
	}

	if app.Css != nil {
		app.Css.Dark = evalRelativePluginUrlPath(app.Css.Dark, app.Id)
		app.Css.Light = evalRelativePluginUrlPath(app.Css.Light, app.Id)
	}

	app.PluginDir = pluginDir
	app.initFrontendPlugin()

	// check if we have child panels
	for _, panel := range Panels {
		if strings.HasPrefix(panel.PluginDir, app.PluginDir) {
			panel.IncludedInAppId = app.Id
			app.Includes = append(app.Includes, &AppIncludeInfo{
				Name: panel.Name,
				Id:   panel.Id,
				Type: panel.Type,
			})
		}
	}

	for _, page := range app.Pages {
		if page.Slug == "" {
			page.Slug = slug.Make(page.Name)
		}
	}

	Apps[app.Id] = app
	return nil
}
开发者ID:kaefik,项目名称:grafana,代码行数:34,代码来源:app_plugin.go


示例3: User

// User handles requests to query some user's info
func (uc *User) User(w *json.Encoder, r *json.Decoder, h *jsonapi.HTTP) {
	res := new(Response)
	var args map[string]interface{}
	if err := r.Decode(&args); err != nil {
		res.Fail("Arguments not in JSON format.")
		return
	}

	ids, ok := args["userid"]
	if !ok {
		res.Fail("No user id passed.").Do(w)
		return
	}

	uids, ok := ids.([]interface{})
	if !ok || len(uids) < 1 {
		res.Fail("No user id passed.").Do(w)
		return
	}

	ret := make([]*model.User, 0, len(uids))
	for _, uid := range uids {
		u, err := model.LoadUser(int(uid.(float64))) // json numbers converts to float64 in go
		if err != nil {
			log.Printf("Error loading user from db: %s", err)
			res.Fail("Error loading user from db").Do(w)
			return
		}
		ret = append(ret, u)
	}
	res.Ok(ret).Do(w)
}
开发者ID:Patrolavia,项目名称:darius,代码行数:33,代码来源:user.go


示例4: UserRepos

func (c *Client) UserRepos(login string) (repos Repos, err error) {
	res, err := c.Get(fmt.Sprintf("orgs/%s", login))
	if err != nil {
		res, err = c.Get(fmt.Sprintf("users/%s/repos", login))
	} else {
		res.Response.Body.Close()
		res, err = c.Get(fmt.Sprintf("orgs/%s/repos", login))
	}
	defer res.Response.Body.Close()
	if err != nil {
		return
	}
	var r Repos
	var dec *json.Decoder
	for res != nil {
		dec = json.NewDecoder(res.Response.Body)
		err = dec.Decode(&r)
		if err != nil {
			return nil, err
		}
		repos = append(repos, r...)
		res = res.NextPage()
	}
	return
}
开发者ID:VictorLowther,项目名称:go-github,代码行数:25,代码来源:repos.go


示例5: Handle

func (h *add) Handle(dec *json.Decoder, httpData *jsonapi.HTTP) (ret interface{}, err error) {
	type p struct {
		Data  Order  `json:"data"`
		Token string `json:"token"`
	}

	var param p
	if err := dec.Decode(&param); err != nil {
		return nil, jsonapi.Error{http.StatusBadRequest, "Parameter is not Order object"}
	}

	if !h.A.Valid(param.Token) {
		return nil, jsonapi.Error{http.StatusForbidden, "Invalid token"}
	}

	// validating data
	data := param.Data
	data.Code = strings.ToUpper(strings.TrimSpace(data.Code))
	if len(data.Code) != 3 || data.Local == 0 || data.Foreign == 0 || data.Time <= 0 {
		return nil, jsonapi.Error{http.StatusBadRequest, "Parameter has no Order object"}
	}

	if _, err := h.M.Insert("orders", data); err != nil {
		return nil, jsonapi.Error{http.StatusInternalServerError, fmt.Sprintf("Error saving order: %s", err)}
	}

	return
}
开发者ID:Ronmi,项目名称:xchg,代码行数:28,代码来源:add.go


示例6: readSumRequest

func readSumRequest(dec *json.Decoder) (interface{}, error) {
	b := make(map[string]interface{})
	if err := dec.Decode(&b); err != nil {
		return nil, err
	}
	return makeSumRequestMap(b)
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:7,代码来源:reqresp.go


示例7: Handle

func (cd *ContainerDaemon) Handle(decoder *json.Decoder) (fds []*os.File, pid int, err error) {
	defer func() {
		if recoveredErr := recover(); recoveredErr != nil {
			err = fmt.Errorf("container_daemon: recovered panic: %s", recoveredErr)
		}
	}()

	var spec garden.ProcessSpec
	err = decoder.Decode(&spec)
	if err != nil {
		return nil, 0, fmt.Errorf("container_daemon: decode process spec: %s", err)
	}

	var cmd *exec.Cmd
	cmd, err = cd.CmdPreparer.PrepareCmd(spec)
	if err != nil {
		return nil, 0, err
	}

	fds, err = cd.Spawner.Spawn(cmd, spec.TTY != nil)
	if err != nil {
		return nil, 0, err
	}

	return fds, cmd.Process.Pid, err
}
开发者ID:julz,项目名称:garden-runc,代码行数:26,代码来源:daemon.go


示例8: Loads

// loads and validate config from config file.
func (c *Config) Loads(conf string) error {
	c.conf = conf

	// read the whole config to []byte.
	var d *json.Decoder
	if f, err := os.Open(conf); err != nil {
		return err
	} else {
		defer f.Close()

		d = json.NewDecoder(NewReader(f))
		//d = json.NewDecoder(f)
	}

	// decode config from stream.
	if err := d.Decode(c); err != nil {
		return err
	}

	// when parse EOF, reparse the config.
	if err := c.reparse(); err != nil {
		return err
	}

	// validate the config.
	if err := c.Validate(); err != nil {
		return err
	}

	return nil
}
开发者ID:thesyncim,项目名称:go-oryx,代码行数:32,代码来源:config.go


示例9: ReceivePackets

// ReceivePacket decodes a packet and adds it to the handler channel
// for processing by the datanode
func ReceivePackets(decoder *json.Decoder, p chan Packet) {
	for {
		r := new(Packet)
		decoder.Decode(r)
		p <- *r
	}
}
开发者ID:sjarvie,项目名称:GoDFS,代码行数:9,代码来源:datanode.go


示例10: xhrSendHandler

func xhrSendHandler(h *handler, w http.ResponseWriter, r *http.Request, sessid string) {
	var messages []string
	var decoder *json.Decoder

	header := w.Header()
	header.Add("Content-Type", "text/plain; charset=UTF-8")
	sid(h, w, r)
	xhrCors(header, r)
	noCache(header)

	s := h.pool.get(sessid)
	if s == nil {
		goto closed
	}

	decoder = json.NewDecoder(r.Body)
	if err := decoder.Decode(&messages); err != nil {
		if err == io.EOF {
			logWriteErr(h.config.Logger, w, s, "Payload expected.")
			return
		}
		logWriteErr(h.config.Logger, w, s, "Broken JSON encoding.")
		return
	}

	for _, v := range messages {
		s.rbufAppend([]byte(v))
	}

	w.WriteHeader(http.StatusNoContent)
	return

closed:
	http.NotFound(w, r)
}
开发者ID:jt6211,项目名称:sockjs-go,代码行数:35,代码来源:xhr.go


示例11: Handle

func (h *listall) Handle(dec *json.Decoder, httpData *jsonapi.HTTP) (result interface{}, err error) {
	type p struct {
		Token string `json:"token"`
	}

	var param p
	if err = dec.Decode(&param); err != nil {
		err = jsonapi.Error{http.StatusBadRequest, fmt.Sprintf("Error decoding parameter: %s", err)}
		return
	}

	if !h.A.Valid(param.Token) {
		err = jsonapi.Error{http.StatusForbidden, "Invalid token"}
		return
	}

	qstr := `SELECT * FROM orders`
	rows := h.M.Query(Order{}, qstr)

	ret := make([]Order, 0)
	for rows.Next() {
		var o Order
		rows.Scan(&o)
		ret = append(ret, o)
	}

	if err = rows.Err(); err != nil {
		err = jsonapi.Error{http.StatusInternalServerError, fmt.Sprintf("Error reading data from database: %s", err)}
		return
	}

	return ret, nil
}
开发者ID:Ronmi,项目名称:xchg,代码行数:33,代码来源:listall.go


示例12: create

func create(storage Storage, resp http.ResponseWriter, vars map[string]string, enc *json.Encoder, dec *json.Decoder) {
	var resource map[string]interface{}
	err := dec.Decode(&resource)

	if err != nil {
		log.Println(err)

		resp.WriteHeader(http.StatusBadRequest)
		err = enc.Encode(apiResponse{"malformed json", "", nil})
		if err != nil {
			log.Println(err)
		}

		return
	}

	// set in storage
	id, stoResp := storage.Create(vars["collection"], resource)

	// write response
	resp.WriteHeader(stoResp.StatusCode())
	err = enc.Encode(apiResponse{stoResp.Error(), id, nil})
	if err != nil {
		log.Println(err)
	}
}
开发者ID:sauerbraten,项目名称:crudapi,代码行数:26,代码来源:api.go


示例13: decodeResponse

func decodeResponse(r *http.Response, key string) (data interface{}, err error) {
	var dec *json.Decoder
	var res map[string]interface{}
	dec = json.NewDecoder(r.Body)
	err = dec.Decode(&res)
	if err != nil {
		if err != io.EOF {
			return
		} else {
			data = make(map[string]interface{})
		}
	}
	if data, ok := res[key]; ok && r.StatusCode < 400 {
		return data, nil
	} else if data, ok := res["error"]; ok && r.StatusCode > 400 {
		if msg, ok := data.(string); ok {
			err := errors.New(msg)
			return nil, err
		}
		return data, nil
	} else if key == "" && r.StatusCode < 400 {
		return nil, nil
	}
	err = errors.New("couldn't read the data")
	return
}
开发者ID:pote,项目名称:webrocket,代码行数:26,代码来源:utils.go


示例14: processPushEvent

func (l *Linter) processPushEvent(decoder *json.Decoder) error {
	event := github.PushEvent{}
	if err := decoder.Decode(&event); err != nil {
		return err
	}

	// By default it returns all open PRs sorted by creation date.
	prs, _, err := l.client.PullRequests.List(*event.Repo.Owner.Name, *event.Repo.Name, nil)
	if err != nil {
		return err
	}

	for _, pr := range prs {
		status, err := l.rebasedStatus(&pr)
		if err != nil {
			return err
		}

		_, _, err = l.client.Repositories.CreateStatus(*event.Repo.Owner.Name, *event.Repo.Name, *pr.Head.SHA, &status)
		if err != nil {
			return err
		}
	}
	return nil
}
开发者ID:eicca,项目名称:ben-ci,代码行数:25,代码来源:linter.go


示例15: readChange

// readChange parses a change from its JSON representation, like so:
//
//	{
//		"t": 12345678,
//		"k": { "fkey": "fvalue", ... },
//		"v": 1.234
//	}
//
func readChange(dec *json.Decoder) (*change, error) {
	b := make(map[string]interface{})
	if err := dec.Decode(&b); err != nil {
		return nil, err
	}
	return makeChangeMap(b)
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:15,代码来源:feature.go


示例16: getVal

func getVal(dec *json.Decoder) (any, error) {
	t, err := dec.Token()
	if err != nil {
		return nil, err
	}

	switch tok := t.(type) {
	case json.Delim:
		switch tok {
		case '[':
			return decToSlice(dec)
		case '{':
			om := New()
			err := om.(*omap).unmarshalJSON(dec)
			if err != nil {
				return nil, err
			}
			_, err = dec.Token() // }
			return om, err
		case ']':
			return nil, endOfSlice
		case '}':
			return nil, fmt.Errorf("unexpected '}'")
		default:
			panic("unreachable code")
		}
	default:
		return tok, nil
	}
}
开发者ID:pocke,项目名称:orderedmap.go,代码行数:30,代码来源:json.go


示例17: decodeObject

func decodeObject(dec *json.Decoder) (Object, error) {
	obj := make(Object)
	for {
		key, err := dec.Token()
		if err != nil {
			return nil, err
		}

		if delim, is := key.(json.Delim); is {
			switch delim {
			case '}':
				return obj, nil
			default:
				return obj, Errorf("Unexpected delim: %s", delim)
			}
		}

		// key is a Value

		value, err := decode(dec)
		obj[key] = value

		if err != nil {
			return obj, err
		}
	}
}
开发者ID:toshaf,项目名称:exhibit,代码行数:27,代码来源:json.go


示例18: LoadMap

func LoadMap(path string) (out *TiledMap, err error) {
	var (
		f       *os.File
		tm      TiledMap
		decoder *json.Decoder
	)
	if f, err = os.Open(path); err != nil {
		return
	}
	defer f.Close()
	decoder = json.NewDecoder(f)
	if err = decoder.Decode(&tm); err != nil {
		return
	}
	for i, ts := range tm.Tilesets {
		tspath := filepath.Join(filepath.Dir(path), ts.Image)
		if tm.Tilesets[i].Texture, err = LoadTexture(tspath, IntNearest, ts.Tilewidth, ts.Tileheight); err != nil {
			return
		}
		// The following ignores spacing, but I don't use it.
		tm.Tilesets[i].Tilecount = (ts.Imagewidth / ts.Tilewidth) * (ts.Imageheight / ts.Tileheight)
		tm.Tilesets[i].Lastgid = ts.Firstgid + tm.Tilesets[i].Tilecount
	}
	out = &tm
	return
}
开发者ID:pikkpoiss,项目名称:ld27,代码行数:26,代码来源:map.go


示例19: decodeArray

func decodeArray(dec *json.Decoder) (Array, error) {
	arr := make(Array, 0)
	for {
		tok, err := dec.Token()
		if err != nil {
			return arr, err
		}

		switch token := tok.(type) {
		case json.Delim:
			switch rune(token) {
			case ']':
				return arr, nil
			case '{':
				obj, err := decodeObject(dec)
				if err != nil {
					return arr, err
				}
				arr = append(arr, obj)
			case '[':
				return decodeArray(dec)
			default:
				return nil, Errorf("Unexpected token %s", token)
			}
		}
	}
}
开发者ID:toshaf,项目名称:exhibit,代码行数:27,代码来源:json.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.Decoder类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang json.Encoder类代码示例发布时间:2022-05-24
下一篇:
Golang json.Unmarshal函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap