Ejemplo n.º 1
0
func showHandler(backend appchilada.Backend) func(http.ResponseWriter, *http.Request) {
	getTemplate := getTemplateFunc("resources/show.html")
	return func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		name := r.URL.Path[len("/show/"):]
		var start, end int64
		if startVal := r.Form.Get("start"); startVal != "" {
			start, _ = strconv.Atoi64(startVal)
		} else {
			// Default to last 24 hours
			start = time.Seconds() - 86400
		}
		if endVal := r.Form.Get("end"); endVal != "" {
			end, _ = strconv.Atoi64(endVal)
		} else {
			// Default to now
			end = time.Seconds()
		}
		results, err := backend.Read(name, appchilada.Interval{start, end})
		if err != nil {
			// TODO Output error in response
			log.Printf("Error getting results for %s: %v", name, err)
			return
		}
		if err := getTemplate().Execute(w, results); err != nil {
			log.Printf("Error executing template: %v", err)
		}
	}
}
Ejemplo n.º 2
0
Archivo: wtf.go Proyecto: J5lx/luminous
func tfquery(req *http.Request) {
	query := strings.Split(req.URL.RawQuery, "&", 0)

	//fmt.Printf("path : %v\n", path)
	//fmt.Printf("query: %v\n", query)

	for i := 0; i < len(query); i++ {
		nv := strings.Split(query[i], "=", 2)
		if len(nv) == 2 {
			switch nv[0] {
			case "b":
				begindate = nv[1]
			case "e":
				enddate = nv[1]
			case "t":
				title, _ = http.URLUnescape(nv[1])
			case "c":
				tcount, _ = strconv.Atoi(nv[1])
			case "l":
				lineheight, _ = strconv.Atoi64(nv[1])
			case "p":
				picwidth, _ = strconv.Atoi64(nv[1])
			case "s":
				spacing, _ = strconv.Atoi(nv[1])
			case "m":
				markerwidth, _ = strconv.Atoi64(nv[1])
			}
		}
		//fmt.Printf("nv: %v\n", nv)
		//showparams("Using  ")
	}
}
Ejemplo n.º 3
0
func checkJoinByteRanges(t *testing.T, inputRangesStr string, expectedRangeStr string) {
	inputRanges := make([]ByteRange, 0, 10)
	appendRange := func(offset int64, length int64) {
		inputRanges = inputRanges[0 : len(inputRanges)+1]
		inputRanges[len(inputRanges)-1] = ByteRange{offset, length}
	}

	for _, rangeStr := range strings.Split(inputRangesStr, ",", -1) {
		//print("Got \"", rangeStr, "\" from input \"", inputRangesStr, "\"\n")
		if len(rangeStr) == 0 {
			// Uh, this is stupid.
			continue
		}
		parts := strings.Split(rangeStr, ":", 2)
		offset, _ := strconv.Atoi64(parts[0])
		length, _ := strconv.Atoi64(parts[1])
		appendRange(offset, length)
	}
	actualRange := joinByteRanges(inputRanges)
	actualRangeStr := actualRange.String()
	if actualRangeStr != expectedRangeStr {
		t.Errorf("Ranges \"%s\": expected compression to %s, actual %s\n", inputRangesStr, expectedRangeStr, actualRangeStr)
		return
	}
}
Ejemplo n.º 4
0
func rateLimitStats(resp *http.Response) {
	if resp == nil {
		return
	}
	curr := time.Seconds()
	reset, _ := strconv.Atoi64(resp.GetHeader("X-RateLimit-Reset"))
	remaining, _ := strconv.Atoi64(resp.GetHeader("X-RateLimit-Remaining"))
	if remaining < 1 && reset-curr > 0 {
		log.Printf("Twitter API limits exceeded. Sleeping for %d seconds.\n", reset-curr)
		time.Sleep((reset - curr) * 1e9)
	}
}
Ejemplo n.º 5
0
// parseRange parses a Range header string as per RFC 2616.
func parseRange(s string, size int64) ([]httpRange, os.Error) {
	if s == "" {
		return nil, nil // header not present
	}
	const b = "bytes="
	if !strings.HasPrefix(s, b) {
		return nil, os.NewError("invalid range")
	}
	var ranges []httpRange
	for _, ra := range strings.Split(s[len(b):], ",", -1) {
		i := strings.Index(ra, "-")
		if i < 0 {
			return nil, os.NewError("invalid range")
		}
		start, end := ra[:i], ra[i+1:]
		var r httpRange
		if start == "" {
			// If no start is specified, end specifies the
			// range start relative to the end of the file.
			i, err := strconv.Atoi64(end)
			if err != nil {
				return nil, os.NewError("invalid range")
			}
			if i > size {
				i = size
			}
			r.start = size - i
			r.length = size - r.start
		} else {
			i, err := strconv.Atoi64(start)
			if err != nil || i > size || i < 0 {
				return nil, os.NewError("invalid range")
			}
			r.start = i
			if end == "" {
				// If no end is specified, range extends to end of the file.
				r.length = size - r.start
			} else {
				i, err := strconv.Atoi64(end)
				if err != nil || r.start > i {
					return nil, os.NewError("invalid range")
				}
				if i >= size {
					i = size - 1
				}
				r.length = i - r.start + 1
			}
		}
		ranges = append(ranges, r)
	}
	return ranges, nil
}
Ejemplo n.º 6
0
func FileHandler(store fs.LocalStore) http.HandlerFunc {
	return func(resp http.ResponseWriter, req *http.Request) {
		setBinaryResp(resp)

		strong, hasStrong := mux.Vars(req)["strong"]
		if !hasStrong {
			writeResponseError(resp, http.StatusInternalServerError,
				"Missing parameter: strong")
			return
		}

		offsetStr, hasOffset := mux.Vars(req)["offset"]
		if !hasOffset {
			writeResponseError(resp, http.StatusInternalServerError,
				"Missing parameter: offset")
			return
		}
		offset, err := strconv.Atoi64(offsetStr)
		if err != nil {
			writeResponseError(resp, http.StatusInternalServerError,
				fmt.Sprintf("Invalid format for length: %s", offsetStr))
			return
		}

		lengthStr, hasLength := mux.Vars(req)["length"]
		if !hasLength {
			writeResponseError(resp, http.StatusInternalServerError,
				"Missing parameter: length")
			return
		}
		length, err := strconv.Atoi64(lengthStr)
		if err != nil {
			writeResponseError(resp, http.StatusInternalServerError,
				fmt.Sprintf("Invalid format for length: %s", lengthStr))
			return
		}

		buffer := bytes.NewBuffer([]byte{})
		n, err := store.ReadInto(strong, offset, length, buffer)
		if err != nil {
			writeResponseError(resp, http.StatusInternalServerError, err.String())
			return
		}
		if n < length {
			writeResponseError(resp, http.StatusInternalServerError, io.ErrShortWrite.String())
		}

		resp.Write(buffer.Bytes())
	}
}
Ejemplo n.º 7
0
func PointFromString(ptstr string) (*Point, os.Error) {
	re := regexp.MustCompile("(-?[0-9]+),(-?[0-9]+),(-?[0-9]+),(-?[0-9]+)")
	matches := re.FindStringSubmatch(ptstr)
	if len(matches) < 5 {
		return nil, os.NewError("invalid pointstring")
	}
	x, ex := strconv.Atoi64(matches[1])
	x2, ex2 := strconv.Atoi64(matches[2])
	y, ey := strconv.Atoi64(matches[3])
	y2, ey2 := strconv.Atoi64(matches[4])
	if ex != nil || ex2 != nil || ey != nil || ey2 != nil {
		return &Point{new(Integer), new(Integer)}, os.NewError("point.FromString: failed to parse coordinates.")
	}
	return &Point{&Integer{x, x2}, &Integer{y, y2}}, nil
}
Ejemplo n.º 8
0
// verifyHmac verifies that a message authentication code (MAC) is valid.
//
// The provided source bytes must be in the form "value|timestamp|message".
func verifyHmac(h hash.Hash, key string, value []byte, timestamp, minAge,
	maxAge int64) ([]byte, error) {
	parts := bytes.SplitN(value, []byte("|"), 3)
	if len(parts) != 3 {
		return nil, ErrAuthentication
	}
	rv := parts[0]
	tst, _ := strconv.Atoi64(string(parts[1]))
	msg := parts[2]
	if tst == 0 {
		return nil, ErrBadTimestamp
	}
	if minAge != 0 && tst > timestamp-minAge {
		return nil, ErrNewTimestamp
	}
	if maxAge != 0 && tst < timestamp-maxAge {
		return nil, ErrOldTimestamp
	}
	// There are several other operations being done by the Encoder so not
	// sure if ConstantTimeCompare() is worth at all.
	msg2 := mac(h, key, rv, tst)
	if len(msg) != len(msg2) || subtle.ConstantTimeCompare(msg, msg2) != 1 {
		return nil, ErrAuthentication
	}
	return rv, nil
}
Ejemplo n.º 9
0
Archivo: asn1.go Proyecto: 8l/go-learn
// Given a tag string with the format specified in the package comment,
// parseFieldParameters will parse it into a fieldParameters structure,
// ignoring unknown parts of the string.
func parseFieldParameters(str string) (ret fieldParameters) {
	for _, part := range strings.Split(str, ",", 0) {
		switch {
		case part == "optional":
			ret.optional = true
		case part == "explicit":
			ret.explicit = true
			if ret.tag == nil {
				ret.tag = new(int)
				*ret.tag = 0
			}
		case strings.HasPrefix(part, "default:"):
			i, err := strconv.Atoi64(part[8:len(part)])
			if err == nil {
				ret.defaultValue = new(int64)
				*ret.defaultValue = i
			}
		case strings.HasPrefix(part, "tag:"):
			i, err := strconv.Atoi(part[4:len(part)])
			if err == nil {
				ret.tag = new(int)
				*ret.tag = i
			}
		}
	}
	return
}
Ejemplo n.º 10
0
Archivo: index.go Proyecto: emepyc/gown
func parseIndexLine(l []byte) (*indexInfo, error) {
	//	fmt.Fprintf (os.Stderr, "Processing line:\n%s\n", l)
	newIndexInfo := indexInfo{}
	var err error
	fields := bytes.Fields(l)
	newIndexInfo.lemma = fields[LEMMA]
	//	newIndexInfo.pos, err = strconv.Atoui64(string(fields[POS]))
	if len(fields[POS]) > 1 {
		return nil, ERR_MSG(SYNTACTIC_CATEGORY_TOO_LONG)
	}
	newIndexInfo.pos = fields[POS][0]

	ptr_cnt, err := strconv.Atoi(string(fields[PTR_CNT]))
	if err != nil {
		return nil, err
	}

	ptr_symbols := fields[SYMBOL : SYMBOL+ptr_cnt]
	newIndexInfo.ptr_symbols = ptr_symbols

	newIndexInfo.tagsense_cnt, err = strconv.Atoi(string(fields[TAGSENSE_CNT+ptr_cnt]))
	if err != nil {
		return nil, err
	}
	offsets_strs := fields[(SYNSET_OFFSET + ptr_cnt - 1):]
	offsets := make([]int64, len(offsets_strs))
	for i, offset := range offsets_strs {
		offsets[i], err = strconv.Atoi64(string(offset))
		if err != nil {
			return nil, err
		}
	}
	newIndexInfo.offsets = offsets
	return &newIndexInfo, nil
}
Ejemplo n.º 11
0
func ParseCase(i int, line string) *Auction {
	a := &Auction{Case: i}
	tokens := strings.Fields(line)
	for p, s := range tokens {
		val, err := strconv.Atoi64(s)
		if err != nil {
			log.Panic(i, line, err)
		}
		switch p {
		case 0:
			a.N = val
		case 1:
			a.P1 = val
		case 2:
			a.W1 = val
		case 3:
			a.M = val
		case 4:
			a.K = val
		case 5:
			a.A = val
		case 6:
			a.B = val
		case 7:
			a.C = val
		case 8:
			a.D = val
		}
	}
	if Debug {
		log.Printf("%#v", *a)
	}
	return a
}
Ejemplo n.º 12
0
func (ctx *Context) GetSecureCookie(name string) (string, bool) {

	cookie, ok := ctx.Request.Cookies[name]

	if !ok {
		return "", false
	}

	parts := strings.Split(cookie, "|", 3)

	val := parts[0]
	timestamp := parts[1]
	sig := parts[2]

	if getCookieSig([]byte(val), timestamp) != sig {
		return "", false
	}

	ts, _ := strconv.Atoi64(timestamp)

	if time.Seconds()-31*86400 > ts {
		return "", false
	}

	buf := bytes.NewBufferString(val)
	encoder := base64.NewDecoder(base64.StdEncoding, buf)

	res, _ := ioutil.ReadAll(encoder)
	return string(res), true
}
Ejemplo n.º 13
0
func decodeSecureCookie(value string) (user string, session string, err os.Error) {
	parts := strings.Split(value, "|", 3)
	if len(parts) != 3 {
		err = os.NewError("Malformed cookie value")
		return
	}
	val := parts[0]
	timestamp := parts[1]
	sig := parts[2]
	// Check signature
	if getCookieSig([]byte(val), timestamp) != sig {
		return "", "", os.NewError("Signature error, cookie is invalid")
	}
	// Check time stamp
	ts, _ := strconv.Atoi64(timestamp)
	if ts+maxAge < time.UTC().Seconds() {
		return "", "", os.NewError("Cookie is outdated")
	}

	buf := bytes.NewBufferString(val)
	encoder := base64.NewDecoder(base64.StdEncoding, buf)
	res, _ := ioutil.ReadAll(encoder)
	str := string(res)
	lst := strings.Split(str, "!", -1)
	if len(lst) != 2 {
		return "", "", os.NewError("Missing !")
	}
	return lst[0], lst[1], nil
}
Ejemplo n.º 14
0
func parseIndexLine(l []byte) *indexInfo {
	//	fmt.Fprintf (os.Stderr, "Processing line:\n%s\n", l)
	newIndexInfo := indexInfo{}
	var err os.Error
	fields := bytes.Fields(l)
	ptr_cnt, err := strconv.Atoi(string(fields[PTR_CNT]))
	if err != nil {
		fmt.Fprintf(os.Stderr, "I had a problem trying to convert '%s' to int\n", fields[PTR_CNT])
		os.Exit(1)
	}
	newIndexInfo.lemma = fields[LEMMA]
	//	newIndexInfo.pos, err = strconv.Atoui64(string(fields[POS]))
	if len(fields[POS]) > 1 {
		fmt.Fprintf(os.Stderr, "POS has to be 1 letter code ('n', 'v', 'a' or 'r') and I have %s\n", fields[POS])
		os.Exit(1)
	}
	newIndexInfo.pos = fields[POS][0]

	newIndexInfo.tagsense_cnt, err = strconv.Atoi(string(fields[TAGSENSE_CNT+ptr_cnt]))
	if err != nil {
		fmt.Fprintf(os.Stderr, "I had a problem trying to convert %s to int32\n", fields[TAGSENSE_CNT+ptr_cnt])
		os.Exit(1)
	}
	offsets_strs := fields[(SYNSET_OFFSET + ptr_cnt):]
	offsets := make([]int64, len(offsets_strs))
	for i, offset := range offsets_strs {
		offsets[i], err = strconv.Atoi64(string(offset))
		if err != nil {
			fmt.Fprintf(os.Stderr, "I had a problem trying to convert the offset %s to int63\n", offset)
			os.Exit(1) // log.Fatal?
		}
	}
	newIndexInfo.offsets = offsets
	return &newIndexInfo
}
Ejemplo n.º 15
0
func (c *Client) FetchVia(b *blobref.BlobRef, v []*blobref.BlobRef) (blobref.ReadSeekCloser, int64, os.Error) {
	url := fmt.Sprintf("%s/camli/%s", c.server, b)

	if len(v) > 0 {
		buf := bytes.NewBufferString(url)
		buf.WriteString("?via=")
		for i, br := range v {
			if i != 0 {
				buf.WriteString(",")
			}
			buf.WriteString(br.String())
		}
		url = buf.String()
	}

	req := http.NewGetRequest(url)

	if c.HasAuthCredentials() {
		req.Header["Authorization"] = c.authHeader()
	}
	resp, err := req.Send()
	if err != nil {
		return nil, 0, err
	}

	var size int64
	if s := resp.GetHeader("Content-Length"); s != "" {
		size, _ = strconv.Atoi64(s)
	}

	return nopSeeker{resp.Body}, size, nil
}
Ejemplo n.º 16
0
func (self FitsHeaderItem) AsInt() int64 {
	value, err := strconv.Atoi64(self.first_token())
	if err != nil {
		return -1
	}
	return value
}
Ejemplo n.º 17
0
// Given a tag string with the format specified in the package comment,
// parseFieldParameters will parse it into a fieldParameters structure,
// ignoring unknown parts of the string.
func parseFieldParameters(str string) (ret fieldParameters) {
	for _, part := range strings.Split(str, ",", -1) {
		switch {
		case part == "optional":
			ret.optional = true
		case part == "explicit":
			ret.explicit = true
			if ret.tag == nil {
				ret.tag = new(int)
				*ret.tag = 0
			}
		case part == "ia5":
			ret.stringType = tagIA5String
		case part == "printable":
			ret.stringType = tagPrintableString
		case strings.HasPrefix(part, "default:"):
			i, err := strconv.Atoi64(part[8:])
			if err == nil {
				ret.defaultValue = new(int64)
				*ret.defaultValue = i
			}
		case strings.HasPrefix(part, "tag:"):
			i, err := strconv.Atoi(part[4:])
			if err == nil {
				ret.tag = new(int)
				*ret.tag = i
			}
		case part == "set":
			ret.set = true
		}
	}
	return
}
Ejemplo n.º 18
0
// Get node value as int64
func (this *Node) I64(namespace, name string) int64 {
	if node := rec_SelectNode(this, namespace, name); node != nil && node.Value != "" {
		n, _ := strconv.Atoi64(node.Value)
		return n
	}
	return 0
}
Ejemplo n.º 19
0
// Get attribute value as int64
func (this *Node) Ai64(namespace, name string) int64 {
	if s := this.As(namespace, name); s != "" {
		n, _ := strconv.Atoi64(s)
		return n
	}
	return 0
}
Ejemplo n.º 20
0
func decode(mutation string) (path, v string, rev int64, keep bool, err error) {
	cm := strings.SplitN(mutation, ":", 2)

	if len(cm) != 2 {
		err = ErrBadMutation
		return
	}

	rev, err = strconv.Atoi64(cm[0])
	if err != nil {
		return
	}

	kv := strings.SplitN(cm[1], "=", 2)

	if err = checkPath(kv[0]); err != nil {
		return
	}

	switch len(kv) {
	case 1:
		return kv[0], "", rev, false, nil
	case 2:
		return kv[0], kv[1], rev, true, nil
	}
	panic("unreachable")
}
Ejemplo n.º 21
0
func (ctx *Context) GetSecureCookie(name string) (string, bool) {
	for _, cookie := range ctx.Request.Cookie {
		if cookie.Name != name {
			continue
		}

		parts := strings.SplitN(cookie.Value, "|", 3)

		val := parts[0]
		timestamp := parts[1]
		sig := parts[2]

		if getCookieSig(ctx.Server.Config.CookieSecret, []byte(val), timestamp) != sig {
			return "", false
		}

		ts, _ := strconv.Atoi64(timestamp)

		if time.Seconds()-31*86400 > ts {
			return "", false
		}

		buf := bytes.NewBufferString(val)
		encoder := base64.NewDecoder(base64.StdEncoding, buf)

		res, _ := ioutil.ReadAll(encoder)
		return string(res), true
	}
	return "", false
}
Ejemplo n.º 22
0
func send(req *http.Request) (resp *http.Response, err os.Error) {
	addr := req.URL.Host
	if !hasPort(addr) {
		addr += ":http"
	}
	conn, err := net.Dial("tcp", "", addr)
	if err != nil {
		return nil, err
	}

	err = req.Write(conn)
	if err != nil {
		conn.Close()
		return nil, err
	}

	reader := bufio.NewReader(conn)
	resp, err = http.ReadResponse(reader, "GET")
	if err != nil {
		conn.Close()
		return nil, err
	}

	r := io.Reader(reader)
	if v := resp.GetHeader("Content-Length"); v != "" {
		n, err := strconv.Atoi64(v)
		if err != nil {
			//			return nil, &badStringError{"invalid Content-Length", v}
		}
		r = io.LimitReader(r, n)
	}
	resp.Body = readClose{r, conn}

	return
}
Ejemplo n.º 23
0
func searchsite(c *appengine.Context, referer string) int64 {
	hash := "ref:" + referer
	item, err := memcache.Get(*c, hash)
	if err != nil {
		q := datastore.NewQuery("MySite").Filter("url", referer)
		log.Print(q)
		/*    t := q.Run(*c)
		/*    var x MySite
		    key, err := t.Next(&x)
		    if err == datastore.Done {
		      //Not found
		      mysite := MySite {
		        url: referer,
		        created: datastore.SecondsToTime(time.Seconds()),
		        views : 1,
		        last_access: datastore.SecondsToTime(time.Seconds()),
		      }
		      key, _ := datastore.Put(*c, datastore.NewIncompleteKey("MySite"), &mysite)
		      return key.IntID()
		    }
		    return key.IntID()
		*/
		return 0
	}
	r, _ := strconv.Atoi64(string(item.Value))
	return r
}
Ejemplo n.º 24
0
// ParseTime parses the time interval from s, and returns it
// as nanoseconds, if it is representable in seconds (with
// isNanoSeconds true), or sample count (with isNanoSeconds false)
// if not.
func ParseTime(s string) (t Time, err os.Error) {
	endi := strings.LastIndexFunc(s, isDigit) + 1
	if endi == 0 {
		return Time{}, os.NewError("invalid number")
	}
	number, suffix := s[0:endi], s[endi:]
	var mult int64
	switch suffix {
	case "s", "":
		mult = 1e9
	case "ms":
		mult = 1e6
	case "us":
		mult = 1e3
	case "ns":
		mult = 1
	case "x": // samples
		mult = 1
	}
	// use exact arithmetic if we can
	d, err := strconv.Atoi64(number)
	if err != nil {
		f, err := strconv.Atof64(number)
		if err != nil {
			return Time{}, err
		}
		d = int64(f * float64(mult))
	} else {
		d *= mult
	}
	return Time{d, suffix != "x"}, nil
}
Ejemplo n.º 25
0
func mustAtoi64(arg string) int64 {
	n, err := strconv.Atoi64(arg)
	if err != nil {
		bail(err)
	}
	return n
}
Ejemplo n.º 26
0
func Import(uid, nick, user, host, ip, hops, ts, name string) os.Error {
	userMutex.Lock()
	defer userMutex.Unlock()

	if _, ok := userMap[uid]; ok {
		return os.NewError("UID collision")
	}

	lownick := parser.ToLower(nick)

	if _, ok := userNicks[lownick]; ok {
		return os.NewError("NICK collision")
	}

	its, _ := strconv.Atoi64(ts)
	u := &User{
		mutex: new(sync.RWMutex),
		ts:    its,
		id:    uid,
		user:  user,
		nick:  nick,
		name:  name,
		utyp:  RegisteredAsUser,
	}

	userMap[uid] = u
	userNicks[lownick] = uid
	return nil
}
Ejemplo n.º 27
0
func (myDHTServer *DHTServerStruct) processNewMessageLog() int {

	//
	// LOCAL
	//

	hid := myDHTServer.getHighestIDForNodeFromDHT(G_nodeID)
	//	myDHTServer.logger.Logf(LMAX, "Highest ID for Node %s is %d", G_nodeID, hid)

	// Query newMessageLog
	sql := fmt.Sprintf("SELECT id,sha1,mailbox,size FROM newMessageLog WHERE id > %d order by id LIMIT 100", hid)
	//	myDHTServer.logger.Logf(LMAX, "processNewMessageLog SQL: %s", sql)
	G_nmlDBLock.Lock()
	stmt, sqlerr := myDHTServer.nml.Prepare(sql)
	defer stmt.Finalize()
	defer G_nmlDBLock.Unlock()
	if sqlerr != nil {
		myDHTServer.logger.Logf(LMIN, "Unexpected error using DB (%s): %s", sql, sqlerr)
		return 0
	}

	// Process results
	count := 0
	var id int
	var sha1 string
	var mailbox string
	var size int
	stmt.Exec()
	for stmt.Next() {
		err := stmt.Scan(&id, &sha1, &mailbox, &size)
		if err != nil {
			myDHTServer.logger.Logf(LMIN, "Unexpected error using DB: %s", err)
			break
		}

		sql := fmt.Sprintf("INSERT INTO DHT (id, sha1, mailbox, cached, size, orignodeid) VALUES (%d, '%s', '%s', NULL, %d, %s)", id, sha1, mailbox, size, G_nodeID)
		myDHTServer.logger.Logf(LMAX, "processNewMessageLog SQL: %s", sql)

		G_dhtDBLock.Lock()
		execerr := myDHTServer.dht.Exec(sql)
		G_dhtDBLock.Unlock()
		if execerr != nil {
			myDHTServer.logger.Logf(LMIN, "processNewMessageLog - Unexpected error using DB (%s): %s", sql, execerr)
		}

		// Update the counters

		// This is bad converting from string to int all the time
		inode, inerr := strconv.Atoi64(G_nodeID)
		if inerr != nil {
			myDHTServer.logger.Log(LMIN, "Unexpected Atoi conversion")
			return 0
		}

		setCounter(NEWMESSAGECOUNTERFILE, inode, uint64(id))
		count += 1
	}

	return count
}
Ejemplo n.º 28
0
func AsInt16(v interface{}) (int16, os.Error) {
	switch value := v.(type) {
	default:
		return 0, os.NewError(fmt.Sprintf("unexpected type: %T", value))
	case int:
		return int16(value), nil
	case int8:
		return int16(value), nil
	case int16:
		return value, nil
	case int32:
		return int16(value), nil
	case int64:
		return int16(value), nil
	case uint:
		return int16(value), nil
	case uint8:
		return int16(value), nil
	case uint16:
		return int16(value), nil
	case uint32:
		return int16(value), nil
	case uint64:
		return int16(value), nil
	case float32:
		return int16(value), nil
	case float64:
		return int16(value), nil
	case string:
		value64, err := strconv.Atoi64(value)
		return int16(value64), err
	}
	panic(fmt.Sprintf("unsupported type: %s", reflect.ValueOf(v).Type().Name()))
}
Ejemplo n.º 29
0
// Scan parses the values of the current result row (set using Result.Next)
// into the given arguments.
func (r *Result) Scan(args ...interface{}) os.Error {
	if len(args) != r.ncols {
		return os.NewError(fmt.Sprintf("incorrect argument count for Result.Scan: have %d want %d", len(args), r.ncols))
	}

	for i, v := range args {
		if int(C.PQgetisnull(r.res, C.int(r.currRow), C.int(i))) == 1 {
			continue
		}
		val := C.GoString(C.PQgetvalue(r.res, C.int(r.currRow), C.int(i)))
		switch v := v.(type) {
		case *[]byte:
			if !strings.HasPrefix(val, "\\x") {
				return argErr(i, "[]byte", "invalid byte string format")
			}
			buf, err := hex.DecodeString(val[2:])
			if err != nil {
				return argErr(i, "[]byte", err.String())
			}
			*v = buf
		case *string:
			*v = val
		case *bool:
			*v = val == "t"
		case *int:
			x, err := strconv.Atoi(val)
			if err != nil {
				return argErr(i, "int", err.String())
			}
			*v = x
		case *int64:
			x, err := strconv.Atoi64(val)
			if err != nil {
				return argErr(i, "int64", err.String())
			}
			*v = x
		case *float32:
			x, err := strconv.Atof32(val)
			if err != nil {
				return argErr(i, "float32", err.String())
			}
			*v = x
		case *float64:
			x, err := strconv.Atof64(val)
			if err != nil {
				return argErr(i, "float64", err.String())
			}
			*v = x
		case *time.Time:
			x, _, err := ParseTimestamp(val)
			if err != nil {
				return argErr(i, "time.Time", err.String())
			}
			*v = *x
		default:
			return os.NewError("unsupported type in Scan: " + reflect.TypeOf(v).String())
		}
	}
	return nil
}
Ejemplo n.º 30
0
func tch_handleComment(session *BlogSession, items []string) string {
	if len(items) < 4 {
		return "syntax: comment <post_id> <your_nick> <your many words of comment>\n"
	}

	post_id, _ := strconv.Atoi64(items[1])
	nick := items[2]
	content := strings.Join(items[3:], " ")

	comment := PostComment{
		Content:   content,
		Author:    nick,
		Timestamp: time.Seconds(),
		PostId:    post_id,
	}

	db := DBGet()
	defer db.Close()

	i, err := db.StoreComment(&comment)
	if err != nil {
		return "error: " + err.String() + "\n"
	}

	s := fmt.Sprintf("commented post %d. your comment's id: %d\n", post_id, i)
	return s
}