示例#1
0
// Expand expands a shortened url to long url.
// It returns the orgin url and nil if success, or empty string
// and an os.Error when failed.
func (req *Googl) Expand(url string) (string, os.Error) {
	res, err := req.get(url)
	if err != nil {
		return "", err
	}

	var temp map[string]string
	if err = json.Unmarshal([]byte(res), &temp); err != nil {
		return "", os.Error(err)
	}

	if _, ok := temp["code"]; ok {
		return "", os.NewError(temp["message"])
	}

	if status, _ := temp["status"]; "OK" != status {
		return "", os.NewError(status)
	}

	url, ok := temp["longUrl"]
	if !ok {
		return "", os.NewError("Invalid response")
	}

	return url, nil
}
示例#2
0
// Project like Expand above.
// But this will return with short URL's analytics as a
// map[string]interface{} type.
func (req *Googl) Project(url, proj string) (map[string]interface{}, os.Error) {
	proj = strings.ToUpper(proj)
	if "FULL" != proj && "ANALYTICS_CLICKS" != proj && "ANALYTICS_TOP_STRINGS" != proj {
		return nil, os.EINVAL
	}

	res, err := req.get(url, map[string]string{"projection": proj})
	if err != nil {
		return nil, err
	}

	var temp map[string]interface{}
	if err = json.Unmarshal([]byte(res), &temp); err != nil {
		return nil, os.Error(err)
	}

	if _, ok := temp["code"]; ok {
		msg, _ := temp["message"].(string)

		return nil, os.NewError(msg)
	}

	if status, _ := temp["status"]; "OK" != status {
		msg, _ := status.(string)

		return nil, os.NewError(msg)
	}

	return temp, nil
}
示例#3
0
func TestDecode(t *testing.T) {
	for _, p := range pairs {
		dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded)))
		count, end, err := StdEncoding.decode(dbuf, []byte(p.encoded))
		testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
		testEqual(t, "Decode(%q) = length %v, want %v", p.encoded, count, len(p.decoded))
		if len(p.encoded) > 0 {
			testEqual(t, "Decode(%q) = end %v, want %v", p.encoded, end, (p.encoded[len(p.encoded)-1] == '='))
		}
		testEqual(t, "Decode(%q) = %q, want %q", p.encoded, string(dbuf[0:count]), p.decoded)

		dbuf, err = StdEncoding.DecodeString(p.encoded)
		testEqual(t, "DecodeString(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
		testEqual(t, "DecodeString(%q) = %q, want %q", string(dbuf), p.decoded)
	}
}
示例#4
0
func (req *Googl) get(url string, params ...map[string]string) (string, os.Error) {
	if !strings.Contains(url, "://goo.gl/") {
		return "", os.EINVAL
	}

	req_url := GOOGL_V1 + "?shortUrl=" + url
	if 0 < len(params) {
		for i := 0; i < len(params); i++ {
			req_url += "&" + toQuery(params[i])
		}
	}

	if "" != req.Key {
		req_url += "&key=" + req.Key
	}

	res, _, err := http.Get(req_url)
	defer res.Body.Close()
	if err != nil {
		return "", os.Error(err)
	}

	body, _ := ioutil.ReadAll(res.Body)

	return string(body), nil
}
示例#5
0
文件: boot.go 项目: foamdino/doozerd
// Elect chooses a seed node, and returns a connection to a cal.
// If this process is the seed, returns nil.
func elect(name, id, laddr string, b *doozer.Conn) *doozer.Conn {
	// advertise our presence, since we might become a cal
	nspath := "/ctl/ns/" + name + "/" + id
	r, err := b.Set(nspath, 0, []byte(laddr))
	if err != nil {
		panic(err)
	}

	// fight to be the seed
	_, err = b.Set("/ctl/boot/"+name, 0, []byte(id))
	switch err {
	case os.Error(doozer.ErrOldRev):
		// we lost, lookup addresses again
		cl := lookupAndAttach(b, name)
		if cl == nil {
			panic("failed to attach after losing election")
		}

		// also delete our entry, since we're not officially a cal yet.
		// it gets set again in peer.Main when we become a cal.
		err := b.Del(nspath, r)
		if err != nil {
			panic(err)
		}

		return cl
	case nil:
		return nil // we are the seed node -- don't attach
	}
	panic(err)
}
示例#6
0
func TestDecode(t *testing.T) {
	for _, p := range gitPairs {
		dbuf := make([]byte, 4*len(p.encoded))
		ndst, err := Decode(dbuf, strings.Bytes(p.encoded))
		testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
		testEqual(t, "Decode(%q) = ndst %v, want %v", p.encoded, ndst, len(p.decoded))
		testEqual(t, "Decode(%q) = %q, want %q", p.encoded, string(dbuf[0:ndst]), p.decoded)
	}
}
示例#7
0
func TestEncoderBuffering(t *testing.T) {
	input := []byte(bigtest.decoded)
	for bs := 1; bs <= 12; bs++ {
		bb := &bytes.Buffer{}
		encoder := NewEncoder(StdEncoding, bb)
		for pos := 0; pos < len(input); pos += bs {
			end := pos + bs
			if end > len(input) {
				end = len(input)
			}
			n, err := encoder.Write(input[pos:end])
			testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, os.Error(nil))
			testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos)
		}
		err := encoder.Close()
		testEqual(t, "Close gave error %v, want %v", err, os.Error(nil))
		testEqual(t, "Encoding/%d of %q = %q, want %q", bs, bigtest.decoded, bb.String(), bigtest.encoded)
	}
}
示例#8
0
func TestAlertForwarding(t *testing.T) {
	c, s := net.Pipe()
	go func() {
		Client(c, testConfig).sendAlert(alertUnknownCA)
		c.Close()
	}()

	err := Server(s, testConfig).Handshake()
	s.Close()
	if e, ok := err.(*net.OpError); !ok || e.Error != os.Error(alertUnknownCA) {
		t.Errorf("Got error: %s; expected: %s", err, alertUnknownCA)
	}
}
示例#9
0
func readFunc(size int) appendFunc {
	return func(f Form, out []byte, s string) []byte {
		out = append(out, s...)
		r := f.Reader(bytes.NewBuffer(out))
		buf := make([]byte, size)
		result := []byte{}
		for n, err := 0, os.Error(nil); err == nil; {
			n, err = r.Read(buf)
			result = append(result, buf[:n]...)
		}
		return result
	}
}
示例#10
0
//first function to get called
func init() {
	http.HandleFunc("/", hello)                            //main page to display
	http.HandleFunc("/recalculate", recalculate)           //page with results
	http.HandleFunc("/keepDataUpToDate", keepDataUpToDate) //function for keeping data up to date

	//initialize variables with dummy values
	LastCheckTime = 0

	CurrentDifficulty = 1.0
	CurrentExchangeRate = 1.0

	//initialize the default values
	DefaultCalc.Difficulty = CurrentDifficulty
	DefaultCalc.HashRate = 100.0
	DefaultCalc.ExchangeRate = CurrentExchangeRate
	DefaultCalc.BitcoinsPerBlock = 50.0
	DefaultCalc.DisplayResults = false

	DefaultCalc.RigCost = 0.0
	DefaultCalc.PowerConsumption = 200.0
	DefaultCalc.PowerCost = 0.1

	DefaultCalc.DifficultyStr = fmt.Sprintf("%.2f", DefaultCalc.Difficulty)
	DefaultCalc.HashRateStr = fmt.Sprintf("%.2f", DefaultCalc.HashRate)
	DefaultCalc.ExchangeRateStr = fmt.Sprintf("%.2f", DefaultCalc.ExchangeRate)
	DefaultCalc.BitcoinsPerBlockStr = fmt.Sprintf("%.2f", DefaultCalc.BitcoinsPerBlock)

	DefaultCalc.RigCostStr = fmt.Sprintf("%.2f", DefaultCalc.RigCost)
	DefaultCalc.PowerConsumptionStr = fmt.Sprintf("%.2f", DefaultCalc.PowerConsumption)
	DefaultCalc.PowerCostStr = fmt.Sprintf("%.2f", DefaultCalc.PowerCost)

	err := os.Error(nil)
	CalcTemplate = template.New(nil)
	CalcTemplate.SetDelims("{{", "}}")                  //changing Delims from {} to {{}} to be able to run the Flattr script
	err = CalcTemplate.ParseFile("tpbitcalc/calc.html") //parses the HTML file. Produces errors if default delims are used because of Flattr code

	//logs an error
	if err != nil {
		log.Print("init err ", err)
		//http.Error(w, err.String(), http.StatusInternalServerError)
		return

	}
}
示例#11
0
// Shorten shortens long url to short url.
// It returns the shortened url and nil if success, or empty
// string and an os.Error when failed.
func (req *Googl) Shorten(url string) (string, os.Error) {
	res, err := req.post(url)
	if err != nil {
		return "", err
	}

	var temp map[string]string
	if err = json.Unmarshal([]byte(res), &temp); err != nil {
		return "", os.Error(err)
	}

	if _, ok := temp["code"]; ok {
		return "", os.NewError(temp["message"])
	}

	id, ok := temp["id"]
	if !ok {
		return "", os.NewError("Invalid response!")
	}

	return id, nil
}
示例#12
0
func (req *Googl) post(url string) (string, os.Error) {
	if strings.Contains(url, "://goo.gl/") {
		return fmt.Sprintf("{\n \"kind\": \"urlshortener#url\",\n \"id\": \"%s\",\n \"longUrl\": \"%s\"\n}", url, url), nil
	}

	req_url := GOOGL_V1
	if "" != req.Key {
		req_url += "?key=" + req.Key
	}

	buf := bytes.NewBuffer(nil)
	buf.WriteString(fmt.Sprintf(`{"longUrl": "%s"}`, url))

	res, err := http.Post(req_url, "application/json", buf)
	if err != nil {
		return "", os.Error(err)
	}

	body, _ := ioutil.ReadAll(res.Body)

	return string(body), nil
}
示例#13
0
文件: all_test.go 项目: WXB506/golang
type DeepEqualTest struct {
	a, b interface{}
	eq   bool
}

var deepEqualTests = []DeepEqualTest{
	// Equalities
	{1, 1, true},
	{int32(1), int32(1), true},
	{0.5, 0.5, true},
	{float32(0.5), float32(0.5), true},
	{"hello", "hello", true},
	{make([]int, 10), make([]int, 10), true},
	{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
	{Basic{1, 0.5}, Basic{1, 0.5}, true},
	{os.Error(nil), os.Error(nil), true},
	{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},

	// Inequalities
	{1, 2, false},
	{int32(1), int32(2), false},
	{0.5, 0.6, false},
	{float32(0.5), float32(0.6), false},
	{"hello", "hey", false},
	{make([]int, 10), make([]int, 11), false},
	{&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
	{Basic{1, 0.5}, Basic{1, 0.6}, false},
	{Basic{1, 0}, Basic{2, 0}, false},
	{map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
	{map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
	{map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
示例#14
0
func TestDecoderBuffering(t *testing.T) {
	for bs := 1; bs <= 12; bs++ {
		decoder := NewDecoder(StdEncoding, bytes.NewBufferString(bigtest.encoded))
		buf := make([]byte, len(bigtest.decoded)+12)
		var total int
		for total = 0; total < len(bigtest.decoded); {
			n, err := decoder.Read(buf[total : total+bs])
			testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, os.Error(nil))
			total += n
		}
		testEqual(t, "Decoding/%d of %q = %q, want %q", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded)
	}
}
示例#15
0
func (n *Network) Whois(target []string, server string) (map[string][]string, os.Error) { //TODO: return a map[string][][]string? map[string][]IrcMessage?
	t := strconv.Itoa64(time.Nanoseconds())
	ret := make(map[string][]string)
	ticker := time.NewTicker(timeout(n.lag))
	myreplies := []string{"ERR_NOSUCHSERVER", "ERR_NONICKNAMEGIVEN",
		"RPL_WHOISUSER", "RPL_WHOISCHANNELS",
		"RPL_WHOISSERVER", "RPL_AWAY",
		"RPL_WHOISOPERATOR", "RPL_WHOISIDLE",
		"ERR_NOSUCHNICK", "RPL_ENDOFWHOIS"}
	repch := make(chan *IrcMessage, 10)
	defer func(myreplies []string, t string) {
		for _, rep := range myreplies {
			n.Listen.DelListener(replies[rep], t)
		}
		return
	}(myreplies, t)
	for _, rep := range myreplies {
		if err := n.Listen.RegListener(replies[rep], t, repch); err != nil {
			ticker.Stop()
			return ret, os.NewError(fmt.Sprintf("Couldn't whois %s=%s: %s", replies[rep], rep, err.String()))
		}
	}

	if server == "" {
		n.queueOut <- &IrcMessage{"", "WHOIS", []string{strings.Join(target, ",")}}
	} else {
		n.queueOut <- &IrcMessage{"", "WHOIS", []string{server, strings.Join(target, ",")}}
	}
	for _, rep := range myreplies {
		ret[replies[rep]] = make([]string, 0)
	}
	done := 0
	err := os.Error(nil)
	for {
		select {
		case m := <-repch:
			ret[m.Cmd] = append(ret[m.Cmd], strings.Join((*m).Params, " "))
			if m.Cmd == replies["RPL_ENDOFWHOIS"] {
				ticker.Stop()
				return ret, err
			} else if m.Cmd == replies["ERR_NOSUCHNICK"] {
				for _, targ := range target {
					if m.Params[1] == targ {
						if err == nil {
							err = os.NewError(fmt.Sprintf("No such nick: %s", targ))
						} else {
							err = os.NewError(fmt.Sprintf("%s, No such nick: %s", err.String(), targ))
						}
						done++
					}
				}
				if done == len(target) {
					return ret, err
				}
			}
			ticker.Stop()
			ticker = time.NewTicker(timeout(n.lag)) //restart the ticker to timeout correctly
		case <-ticker.C:
			ticker.Stop()
			return ret, err
		}
	}
	ticker.Stop()
	return ret, err //BUG: why do we need this?
}