本文整理匯總了Golang中encoding/json.Decoder.Decode方法的典型用法代碼示例。如果您正苦於以下問題:Golang Decoder.Decode方法的具體用法?Golang Decoder.Decode怎麽用?Golang Decoder.Decode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類encoding/json.Decoder
的用法示例。
在下文中一共展示了Decoder.Decode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: CountFacebookShares
func CountFacebookShares(r *Request) *Result {
var (
resp *http.Response
dec *json.Decoder
err error
feed map[string]facebookFeed
url = r.Url()
feedUrl = fmt.Sprintf(facebookFeedUrl, url)
)
if resp, err = http.Get(feedUrl); err != nil {
return Empty
}
dec = json.NewDecoder(resp.Body)
if err = dec.Decode(&feed); err != nil {
return Empty
}
feedForUrl, ok := feed[url]
if !ok {
return Empty
}
return &Result{Points: feedForUrl.Shares}
}
示例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
}
示例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)
}
示例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
}
示例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(¶m); 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
}
示例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)
}
示例7: 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(¶m); 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
}
示例8: 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
}
}
示例9: 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
}
示例10: 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)
}
}
示例11: 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"
}
示例12: Create
// Create hadles requests to create pad
func (pc *Pad) Create(w *json.Encoder, r *json.Decoder, h *jsonapi.HTTP) {
res := new(Response)
u, err := Me(pc.SF.Get(h.Request))
if err != nil {
res.Err(1, "Not logged in").Do(w)
return
}
if !validEditor(pc.Config, u) {
res.Err(3, "Not valid editor").Do(w)
return
}
var data CreateRequest
if err := r.Decode(&data); err != nil {
log.Printf("Failed to parse postdata: %s", err)
res.Err(2, "Data error").Do(w)
return
}
p, err := model.NewPad(pc.DB, u.ID, data.Title, data.Content, data.Tags, data.Coops)
if err != nil {
log.Printf("Failed creating pad: %s", err)
res.Err(2, "Database error").Do(w)
return
}
resData := map[string]int{
"code": 0,
"id": p.ID,
}
res.Ok(resData).Do(w)
}
示例13: loopStdout
func (m *MCP) loopStdout(dec *json.Decoder) {
for {
blob := &messages.Blob{}
err := dec.Decode(blob)
if err == io.EOF {
m.debugHandler("EOF from STDIN")
return
} else if err != nil {
m.debugHandler("Decoding JSON from child STDIN: %v", err)
if err := m.Stop(); err != nil {
log.Fatal(err)
}
}
switch blob.Type {
case messages.BlobTypeRequest:
go m.handleRequest(blob.Request)
case messages.BlobTypeConstruct:
go m.constructDone(blob.Construct)
case messages.BlobTypeResponse:
go m.handleResponse(blob.Response)
case messages.BlobTypeDestruct:
go m.destructDone(blob.Destruct)
default:
m.debugHandler("Unknown blob type %v", blob.Type)
if err := m.Stop(); err != nil {
log.Fatal(err)
}
}
}
}
示例14: UpdateProfile
func UpdateProfile(wr http.ResponseWriter, req *http.Request) {
var (
decoder *json.Decoder
profile *data.Profile
err error
encoder *json.Encoder
)
decoder = json.NewDecoder(req.Body)
profile = data.NewProfile()
encoder = json.NewEncoder(wr)
if err = decoder.Decode(profile); nil != err {
wr.WriteHeader(http.StatusBadRequest)
encoder.Encode(NewErrorJSONBadRequest())
return
}
if err = profile.Update(); err != nil {
log.Printf("error occurred saving profile %s ", err.Error())
wr.WriteHeader(http.StatusInternalServerError)
encoder.Encode(NewErrorJSONUnexpectedError(err.Error()))
return
}
encoder.Encode(profile)
}
示例15: 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)
}