Exemplo n.º 1
0
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}
}
Exemplo n.º 2
0
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
}
Exemplo n.º 3
0
// 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)
}
Exemplo n.º 4
0
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
}
Exemplo n.º 5
0
Arquivo: add.go Projeto: Ronmi/xchg
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
}
Exemplo n.º 6
0
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)
}
Exemplo n.º 7
0
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
}
Exemplo n.º 8
0
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
}
Exemplo n.º 9
0
// 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
	}
}
Exemplo n.º 10
0
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
}
Exemplo n.º 11
0
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)
	}
}
Exemplo n.º 12
0
// 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"
}
Exemplo n.º 13
0
// 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)
}
Exemplo n.º 14
0
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)
			}
		}
	}
}
Exemplo n.º 15
0
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)
}
Exemplo n.º 16
0
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)
}
Exemplo n.º 17
0
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
}
Exemplo n.º 18
0
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
}
Exemplo n.º 19
0
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
}
Exemplo n.º 20
0
// 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
}
Exemplo n.º 21
0
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
	}
}
Exemplo n.º 22
0
// 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)
}
Exemplo n.º 23
0
// 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)
}
Exemplo n.º 24
0
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{})
			}
		}
	}
}
Exemplo n.º 25
0
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
}
Exemplo n.º 26
0
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
}
Exemplo n.º 27
0
// 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)
}
Exemplo n.º 28
0
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)

}
Exemplo n.º 29
0
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)
	}
}
Exemplo n.º 30
0
func CreateProject(wr http.ResponseWriter, req *http.Request) {
	var (
		decoder *json.Decoder
		encoder *json.Encoder
		proj    *data.Project
		err     error
	)

	decoder = json.NewDecoder(req.Body)
	encoder = json.NewEncoder(wr)
	proj = data.NewProject()

	if err = decoder.Decode(proj); err != nil {
		log.Println(err.Error())
		wr.WriteHeader(http.StatusBadRequest)
		encoder.Encode(NewErrorJSON(err.Error(), 400))
		return
	}

	if _, err = proj.Save(); err != nil {
		log.Println(err.Error())
		wr.WriteHeader(http.StatusInternalServerError)
		encoder.Encode(NewErrorJSONUnexpectedError(err.Error()))
		return
	}

	wr.WriteHeader(http.StatusCreated)
	encoder.Encode(proj)
}