Пример #1
0
func iotPost(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Post")
	// receive posted data
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println(err)
		fmt.Fprint(w, "IoT failed")
		return
	}
	json, err := simplejson.NewJson(body)
	if err != nil {
		fmt.Println("error in NewJson:", err)
		return
	}
	payload := json.Get("payload")
	payload_str, err := payload.String()
	if err != nil {
		fmt.Println("Couldn't get payload")
		return
	}
	created_at, err := json.Get("created_at").String()
	if err != nil {
		// If the created at time doesn't come with the
		// JSON object then generate it with RFC3339 format
		t := time.Now()
		created_at = t.UTC().Format("2006-01-02T15:04:05Z07:00")
	}
	fmt.Println("Got payload " + payload_str + " at " + created_at)
	renderOk(w, []byte(`{"content": body}`))
}
Пример #2
0
func BenchmarkGoSimplejsonSmall(b *testing.B) {
	for i := 0; i < b.N; i++ {
		json, _ := simplejson.NewJson(smallFixture)

		json.Get("uuid").String()
		json.Get("tz").Float64()
		json.Get("ua").String()
		json.Get("st").Float64()

		nothing()
	}
}
Пример #3
0
func BenchmarkUjsonSmall(b *testing.B) {
	for i := 0; i < b.N; i++ {
		json, _ := ujson.NewFromBytes(smallFixture)

		json.Get("uuid").String()
		json.Get("tz").Float64()
		json.Get("ua").String()
		json.Get("st").Float64()

		nothing()
	}
}
Пример #4
0
/*
   github.com/bitly/go-simplejson
*/
func BenchmarkGoSimpleJsonMedium(b *testing.B) {
	for i := 0; i < b.N; i++ {
		json, _ := simplejson.NewJson(mediumFixture)
		person := json.Get("person")
		person.Get("name").Get("fullName").String()
		person.Get("github").Get("followers").Float64()
		json.Get("company")
		arr, _ := person.Get("gravatar").Get("avatars").Array()

		for _, el := range arr {
			nothing(el.(map[string]interface{})["url"])
		}
	}
}
Пример #5
0
func (s *Server) ListTables() ([]string, error) {
	var tables []string

	query := NewEmptyQuery()

	jsonResponse, err := s.queryServer(target("ListTables"), query)

	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return nil, err
	}

	response, err := json.Get("TableNames").Array()

	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	for _, value := range response {
		if t, ok := (value).(string); ok {
			tables = append(tables, t)
		}
	}

	return tables, nil
}
Пример #6
0
func (batchWriteItem *BatchWriteItem) Execute() (map[string]interface{}, error) {
	q := NewEmptyQuery()
	q.AddWriteRequestItems(batchWriteItem.ItemActions)

	jsonResponse, err := batchWriteItem.Server.queryServer(target("BatchWriteItem"), q)

	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return nil, err
	}

	unprocessed, err := json.Get("UnprocessedItems").Map()
	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	if len(unprocessed) == 0 {
		return nil, nil
	} else {
		return unprocessed, errors.New("One or more unprocessed items.")
	}

}
Пример #7
0
func BenchmarkUjsonMedium(b *testing.B) {
	for i := 0; i < b.N; i++ {
		json, _ := ujson.NewFromBytes(mediumFixture)

		person := json.Get("person")

		person.Get("name").Get("fullName").String()
		person.Get("github").Get("followers").Float64()
		json.Get("company").String()

		arr := person.Get("gravatar").Get("avatars").Array()
		for _, el := range arr {
			el.Get("url").String()
		}

		nothing()
	}
}
Пример #8
0
func StartClient(configFile string, done chan bool) {
	b, err := ioutil.ReadFile(configFile)
	if err != nil {
		fmt.Println(configFile, " not found")
		go func() {
			done <- false
		}()
		return
	}
	json, _ := simplejson.NewJson(b)
	ip := json.Get("ip").MustString("127.0.0.1")
	port := json.Get("port").MustInt(6776)

	monitors := json.Get("monitors").MustMap()

	for k, v := range monitors {
		monitored, _ := v.(string)
		go startWork(ip, port, k, monitored, time.Minute)
	}
}
Пример #9
0
func TrySimpleJson() {
	body := []byte(jsonString)
	json, _ := simplejson.NewJSON(body)
	P(json.Get("data", "content", "body").String())
	content := json.Get("data", "content")
	P("content on *json-type: ", content)
	byte_data, _ := json.Get("data", "content").MarshalJSON()
	// P("not marshaled, just use string(): ", string(json.Get("data", "content")))		// failed
	P("content MarshalJsoned: ", string(byte_data))
	// not follow at archture:
	P("not follow archery: ", json.Get("title"))

	json2_byte := []byte(json2)
	json, _ = simplejson.NewJSON(json2_byte)
	// for i, v := range json.Get("conversations").Array() {
	//  P(i, v)
	// }
	qa_activity := json.Get("conversations").JSONArray()[0].Get("data", "qa_activity")
	qa_activity1, _ := qa_activity.MarshalJSON()
	P("stringed qa_activity", string(qa_activity1))
	P("action: ", qa_activity.Get("action").String())
	P("num_unread: ", qa_activity.Get("num_unread").Int())
	P("thread_id: ", qa_activity.Get("thread_id").String())
	data_raw := json.Get("conversations").JSONArray()[0].Get("data_raw").String()
	P("raw_data_raw: ", data_raw)
}
Пример #10
0
func (p *SonyXperiaProvider) GetEmailAddress(s *SessionState) (string, error) {
	req, err := http.NewRequest("GET",
		p.ProfileUrl.String()+"?access_token="+s.AccessToken, nil)
	if err != nil {
		log.Printf("failed building request %s", err)
		return "", err
	}
	json, err := api.Request(req)
	if err != nil {
		log.Printf("failed making request %s", err)
		return "", err
	}
	return json.Get("email").String()
}
Пример #11
0
func (batchGetItem *BatchGetItem) Execute() (map[string][]map[string]*Attribute, error) {
	q := NewEmptyQuery()
	q.AddGetRequestItems(batchGetItem.Keys)

	jsonResponse, err := batchGetItem.Server.queryServer(target("BatchGetItem"), q)
	if err != nil {
		return nil, err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return nil, err
	}

	results := make(map[string][]map[string]*Attribute)

	tables, err := json.Get("Responses").Map()
	if err != nil {
		message := fmt.Sprintf("Unexpected response %s", jsonResponse)
		return nil, errors.New(message)
	}

	for table, entries := range tables {
		var tableResult []map[string]*Attribute

		jsonEntriesArray, ok := entries.([]interface{})
		if !ok {
			message := fmt.Sprintf("Unexpected response %s", jsonResponse)
			return nil, errors.New(message)
		}

		for _, entry := range jsonEntriesArray {
			item, ok := entry.(map[string]interface{})
			if !ok {
				message := fmt.Sprintf("Unexpected response %s", jsonResponse)
				return nil, errors.New(message)
			}

			unmarshalledItem := parseAttributes(item)
			tableResult = append(tableResult, unmarshalledItem)
		}

		results[table] = tableResult
	}

	return results, nil
}
Пример #12
0
func (p *PhabricatorProvider) GetEmailAddress(s *SessionState) (string, error) {
	req, err := http.NewRequest("GET",
		p.ProfileUrl.String()+"?access_token="+s.AccessToken, nil)
	if err != nil {
		log.Printf("failed building request %s", err)
		return "", err
	}
	var resp *http.Response
	var client *http.Client
	// Temporarily adding insecure certificate bypass for testing
	allow_insecure := true
	if allow_insecure {
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		client = &http.Client{Transport: tr}
	} else {
		client = http.DefaultClient
	}
	resp, err = client.Do(req)
	if err != nil {
		log.Printf("%s %s %s", req.Method, req.URL, err)
		return "", err
	}
	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	log.Printf("%d %s %s %s", resp.StatusCode, req.Method, req.URL, body)
	if err != nil {
		log.Printf("%s %s %s", req.Method, req.URL, err)
		return "", err
	}
	if resp.StatusCode != 200 {
		log.Printf("%s %s %s", req.Method, req.URL, err)
		return "", err
	}
	json, err := simplejson.NewJson(body)
	if err != nil {
		log.Printf("%s %s %s", req.Method, req.URL, err)
		return "", err
	}
	//	json, err := api.Request(req)
	if err != nil {
		log.Printf("failed making request %s", err)
		return "", err
	}
	return json.Get("result").Get("primaryEmail").String()
}
Пример #13
0
func (s *Server) ListTablesCallbackIterator(cb func(string)) error {
	var lastEvaluatedTableName string

	for {
		query := NewEmptyQuery()
		query.AddExclusiveStartTableName(lastEvaluatedTableName)

		jsonResponse, err := s.queryServer(target("ListTables"), query)
		if err != nil {
			return err
		}

		json, err := simplejson.NewJson(jsonResponse)
		if err != nil {
			return err
		}

		lastEvaluatedTableName = ""
		if json, ok := json.CheckGet("LastEvaluatedTableName"); ok {
			lastEvaluatedTableName, err = json.String()
			if err != nil {
				message := fmt.Sprintf("Unexpected response %s", jsonResponse)
				return errors.New(message)
			}
		}

		response, err := json.Get("TableNames").Array()
		if err != nil {
			message := fmt.Sprintf("Unexpected response %s", jsonResponse)
			return errors.New(message)
		}

		for _, value := range response {
			if t, ok := (value).(string); ok {
				cb(t)
			}
		}
		if lastEvaluatedTableName == "" {
			break
		}
	}

	return nil

}
Пример #14
0
func (s *Server) DeleteTable(tableDescription TableDescriptionT) (string, error) {
	query := NewEmptyQuery()
	query.AddDeleteRequestTable(tableDescription)

	jsonResponse, err := s.queryServer(target("DeleteTable"), query)

	if err != nil {
		return "unknown", err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return "unknown", err
	}

	return json.Get("TableDescription").Get("TableStatus").MustString(), nil
}
Пример #15
0
func (s *Server) GetShardIterator(streamArn, shardId, shardIteratorType, sequenceNumber string) (string, error) {
	query := NewEmptyQuery()
	query.AddStreamArn(streamArn)
	query.AddShardId(shardId)
	query.AddShardIteratorType(shardIteratorType)

	if len(sequenceNumber) != 0 {
		query.AddSequenceNumber(sequenceNumber)
	}

	jsonResponse, err := s.queryServer(streamsTarget("GetShardIterator"), query)

	if err != nil {
		return "unknown", err
	}

	json, err := simplejson.NewJson(jsonResponse)

	if err != nil {
		return "unknown", err
	}

	return json.Get("ShardIterator").MustString(), nil
}
Пример #16
0
func main() {
	_, err := os.Stat("log")
	if err != nil {
		os.Mkdir("log", os.ModePerm)
	}

	if _, err := os.Stat("log/master.log"); err == nil {
		os.Remove("log/master.log")
	}

	log.WriteToFile("log/master.log")

	defer func() {
		if e := recover(); e != nil {
			log.LogFatalf(e)
			time.Sleep(1 * time.Second)
		}
	}()

	flag.Parse()
	if *config == "" {
		flag.PrintDefaults()
		return
	}

	m := master.NewMaster()
	apps := *config + "/app.json"
	appdata, e := ioutil.ReadFile(apps)
	if e != nil {
		panic(e)
	}

	var app master.App
	if err := json.Unmarshal(appdata, &app); err != nil {
		panic(err)
	}

	m.AppDef = app
	servers := *config + "/servers.json"
	json, err := readConfig(servers)
	if err != nil {
		panic(err)
	}

	def, err1 := json.Map()
	if err1 != nil {
		panic(err1)
	}
	for key := range def {
		if key == "master" {
			mst := json.Get(key)
			if host, ok := mst.CheckGet("host"); ok {
				v, err := host.String()
				if err != nil {
					panic(err)
				}

				m.Host = v
			} else {
				m.Host = "127.0.0.1"
			}

			if localip, ok := mst.CheckGet("localip"); ok {
				v, err := localip.String()
				if err != nil {
					panic(err)
				}

				m.LocalIP = v
			} else {
				m.LocalIP = "127.0.0.1"
			}

			if outerip, ok := mst.CheckGet("outerip"); ok {
				v, err := outerip.String()
				if err != nil {
					panic(err)
				}

				m.OuterIP = v
			} else {
				m.OuterIP = "127.0.0.1"
			}

			if port, ok := mst.CheckGet("port"); ok {
				v, err := port.Int()
				if err != nil {
					panic(err)
				}

				m.Port = v
			} else {
				m.Port = 5100
			}

			if agent, ok := mst.CheckGet("agent"); ok {
				v, err := agent.Bool()
				if err != nil {
					panic(err)
				}

				m.Agent = v
			}

			if agentid, ok := mst.CheckGet("agentid"); ok {
				v, err := agentid.String()
				if err != nil {
					panic(err)
				}

				m.AgentId = v
			}

			if cp, ok := mst.CheckGet("consoleport"); ok {
				v, err := cp.Int()
				if err != nil {
					panic(err)
				}

				m.ConsolePort = v
			}

			if tpl, ok := mst.CheckGet("consoleroot"); ok {
				v, err := tpl.String()
				if err != nil {
					panic(err)
				}
				log.LogMessage("path:", v)
				m.Template = v
			}

			if waits, ok := mst.CheckGet("waitagents"); ok {
				v, err := waits.Int()
				if err != nil {
					panic(err)
				}

				m.WaitAgents = v
			}

			if startuid, ok := mst.CheckGet("startuid"); ok {
				v, err := startuid.Int()
				if err != nil {
					panic(err)
				}

				master.AppUid = int32(v)
			}

			if nobalance, ok := mst.CheckGet("nobalance"); ok {
				v, err := nobalance.Bool()
				if err != nil {
					panic(err)
				}

				m.NoBalance = v
			}

			continue

		}

		m.AppArgs[key], _ = json.Get(key).MarshalJSON()
	}

	exitChan := make(chan int)
	signalChan := make(chan os.Signal, 1)
	go func() {
		<-signalChan
		exitChan <- 1
	}()
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	m.Start()
	m.Wait(exitChan)
	m.Exit()
	log.CloseLogger()
}