// 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" }
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 }
// 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) }
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 }
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 }
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) }
func decodeConfiguration(decoder *json.Decoder) (*Configuration, error) { var config Configuration err := decoder.Decode(&config) if err != nil { return nil, err } if config.ClusterId == "" { return nil, fmt.Errorf("Invalid configuration cluster id must not be empty") } if config.Version < 1 { return nil, fmt.Errorf("Invalid configuration version (must be > 0): %v", config.Version) } if len(config.Hosts) == 0 { return nil, fmt.Errorf("Invalid configuration: empty hosts") } twoFInc := (2 * int(config.F)) + 1 if twoFInc > len(config.Hosts) { return nil, fmt.Errorf("F given as %v, requires minimum 2F+1=%v hosts but only %v hosts specified.", config.F, twoFInc, len(config.Hosts)) } if int(config.MaxRMCount) < len(config.Hosts) { return nil, fmt.Errorf("MaxRMCount given as %v but must be at least the number of hosts (%v).", config.MaxRMCount, len(config.Hosts)) } for idx, hostPort := range config.Hosts { port := common.DefaultPort hostOnly := hostPort if host, portStr, err := net.SplitHostPort(hostPort); err == nil { portInt64, err := strconv.ParseUint(portStr, 0, 16) if err != nil { return nil, err } port = int(portInt64) hostOnly = host } hostPort = net.JoinHostPort(hostOnly, fmt.Sprint(port)) config.Hosts[idx] = hostPort if _, err := net.ResolveTCPAddr("tcp", hostPort); err != nil { return nil, err } } if len(config.ClientCertificateFingerprints) == 0 { return nil, errors.New("No ClientCertificateFingerprints defined") } else { fingerprints := make(map[[sha256.Size]byte]server.EmptyStruct, len(config.ClientCertificateFingerprints)) for _, fingerprint := range config.ClientCertificateFingerprints { fingerprintBytes, err := hex.DecodeString(fingerprint) if err != nil { return nil, err } else if l := len(fingerprintBytes); l != sha256.Size { return nil, fmt.Errorf("Invalid fingerprint: expected %v bytes, and found %v", sha256.Size, l) } ary := [sha256.Size]byte{} copy(ary[:], fingerprintBytes) fingerprints[ary] = server.EmptyStructVal } config.fingerprints = fingerprints config.ClientCertificateFingerprints = nil } return &config, err }
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 }
// 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 }
// 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 } }
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) }
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 }
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) } }
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 }
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 }
// 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) }
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 } }
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 } } }
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 }
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) } } } }
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 } }
func store_read(wsData *webserverData) { // initialize store if not already initialized, if there was any corruption issue // then delete the whole file and start over (via delete_store()) if store == nil { // following code from http://stackoverflow.com/questions/16681003/how-do-i-parse-a-json-file-into-a-struct-with-go var file *os.File var err error if file, err = os.Open(wsData.storeFilespec); err != nil { delete_store(wsData) } else { defer func() { if file != nil { file.Close() } }() // see http://blog.golang.org/json-and-go for arbitrary json var allStore interface{} var jsonParser *json.Decoder = json.NewDecoder(file) if err = jsonParser.Decode(&allStore); err != nil { file.Close() file = nil delete_store(wsData) } else { store = allStore.(map[string]interface{}) } } } }
// serveWriteJSON receives incoming series data in JSON and writes it to the database. func (h *Handler) serveWriteJSON(w http.ResponseWriter, r *http.Request, body []byte, user *meta.UserInfo) { var bp client.BatchPoints var dec *json.Decoder dec = json.NewDecoder(bytes.NewReader(body)) if err := dec.Decode(&bp); err != nil { if err.Error() == "EOF" { w.WriteHeader(http.StatusOK) return } resultError(w, influxql.Result{Err: err}, http.StatusBadRequest) return } if bp.Database == "" { resultError(w, influxql.Result{Err: fmt.Errorf("database is required")}, http.StatusBadRequest) return } if di, err := h.MetaStore.Database(bp.Database); err != nil { resultError(w, influxql.Result{Err: fmt.Errorf("metastore database error: %s", err)}, http.StatusInternalServerError) return } else if di == nil { resultError(w, influxql.Result{Err: fmt.Errorf("database not found: %q", bp.Database)}, http.StatusNotFound) return } if h.requireAuthentication && user == nil { resultError(w, influxql.Result{Err: fmt.Errorf("user is required to write to database %q", bp.Database)}, http.StatusUnauthorized) return } if h.requireAuthentication && !user.Authorize(influxql.WritePrivilege, bp.Database) { resultError(w, influxql.Result{Err: fmt.Errorf("%q user is not authorized to write to database %q", user.Name, bp.Database)}, http.StatusUnauthorized) return } points, err := NormalizeBatchPoints(bp) if err != nil { resultError(w, influxql.Result{Err: err}, http.StatusBadRequest) return } // Convert the json batch struct to a points writer struct if err := h.PointsWriter.WritePoints(&cluster.WritePointsRequest{ Database: bp.Database, RetentionPolicy: bp.RetentionPolicy, ConsistencyLevel: cluster.ConsistencyLevelOne, Points: points, }); influxdb.IsClientError(err) { resultError(w, influxql.Result{Err: err}, http.StatusBadRequest) return } else if err != nil { resultError(w, influxql.Result{Err: err}, http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) }
func (c *Client) GetPullRequests(login, repo, state string) (pulls PullRequests, err error) { var prq_state string switch state { case "": prq_state = "open" case "open", "closed": prq_state = state default: return nil, errors.New("state must be either open or closed.") } res, err := c.Get(fmt.Sprintf("repos/%s/%s/pulls?state=%s", login, repo, prq_state)) if err != nil { return } var p PullRequests var dec *json.Decoder for res != nil { dec = json.NewDecoder(res.Response.Body) err = dec.Decode(&p) res.Response.Body.Close() if err != nil { return nil, err } pulls = append(pulls, p...) res = res.NextPage() } return }
func (l *LibvirtLXCBackend) RestoreState(jobs map[string]*host.ActiveJob, dec *json.Decoder) error { containers := make(map[string]*libvirtContainer) if err := dec.Decode(&containers); err != nil { return err } for _, j := range jobs { container, ok := containers[j.Job.ID] if !ok { continue } container.l = l container.job = j.Job container.done = make(chan struct{}) status := make(chan error) go container.watch(status) if err := <-status; err != nil { // log error l.state.RemoveJob(j.Job.ID) container.cleanup() continue } l.containers[j.Job.ID] = container for _, p := range j.Job.Config.Ports { l.ports[p.Proto].GetPort(uint16(p.Port)) } } return nil }
func CreateProfile(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); err != nil { http.Error(wr, err.Error(), http.StatusBadRequest) return } if profile.Exists(profile.Email) { wr.WriteHeader(http.StatusConflict) encoder.Encode(NewErrorJSONExists()) return } if _, err = profile.Save(); err != nil { log.Printf("error occurred saving profile %s ", err.Error()) wr.WriteHeader(http.StatusInternalServerError) encoder.Encode(NewErrorJSONUnexpectedError(err.Error())) return } encoder.Encode(profile) //get handle to email channel and send email to user go service.SendMailTemplate(service.MAIL_TEMPLATE_INTEREST, service.NewMailSender(), service.MAIL_FROM, profile.Email) }
// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. // This function is lenient and will decode any options permutations of the // related Marshaler. func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error { inputValue := json.RawMessage{} if err := dec.Decode(&inputValue); err != nil { return err } return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil) }
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) }
func TestParsing(t *testing.T) { addresses := []string{ "1DgxRTofdbau7kpf3pQeRydcoTPG2L5NUX", "17Nt7rWiRZKDgcNp421zZ1FHGPWSnnT1bk", } var decoder *json.Decoder if true { response, err := http.Get(url) if err != nil { t.SkipNow() // log.Fatal(err) } defer response.Body.Close() decoder = json.NewDecoder(response.Body) } r := new(OverviewReport) err := decoder.Decode(&r) if err != nil { t.Fail() // log.Fatal(err) } total := new(AddressReport) for _, address := range addresses { report, ok := r.Report[address] if !ok { t.Fail() } total.Add(report) } }
// 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) }