當前位置: 首頁>>代碼示例>>Golang>>正文


Golang json.Decoder類代碼示例

本文整理匯總了Golang中encoding/json.Decoder的典型用法代碼示例。如果您正苦於以下問題:Golang Decoder類的具體用法?Golang Decoder怎麽用?Golang Decoder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Decoder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的encoding/json.Decoder類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。