本文整理匯總了Golang中menteslibres/net/gosexy/to.Int64函數的典型用法代碼示例。如果您正苦於以下問題:Golang Int64函數的具體用法?Golang Int64怎麽用?Golang Int64使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Int64函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestGet
func TestGet(t *testing.T) {
settings, err := Open("_examples/input/settings.yaml")
if err != nil {
t.Errorf("Test failed.")
}
test1 := "Hello World!"
val1 := to.String(settings.Get("test_string"))
if val1 != test1 {
t.Errorf("Got %t expecting %t.", val1, test1)
}
val2 := int(to.Int64(settings.Get("non_defined_int")))
if val2 != 0 {
t.Errorf("Test failed.")
}
test3 := "Third"
val3 := settings.Get("test_map", "element_3", "test_sequence").([]interface{})
if val3[2] != test3 {
t.Errorf("Got %t expecting %t.", val3[2], test3)
}
test5 := "Hello World!"
val5 := to.String(settings.Get("test_string"))
if test5 != val5 {
t.Errorf("Got %t expecting %t.", test5, val5)
}
test6 := 1234
val6 := int(to.Int64(settings.Get("test_int")))
if test6 != val6 {
t.Errorf("Got %t expecting %t.", test6, val6)
}
test7 := float64(1.2)
val7 := to.Float64(settings.Get("test_float"))
if test7 != val7 {
t.Errorf("Got %t expecting %t.", test7, val7)
}
test8 := true
val8 := to.Bool(settings.Get("test_bool"))
if test8 != val8 {
t.Errorf("Got %t expecting %t.", test8, val8)
}
}
示例2: TestAppend
// This test appends some data into the "artist" table.
func TestAppend(t *testing.T) {
var err error
var id interface{}
// Opening database.
sess, err := db.Open(wrapperName, settings)
if err != nil {
t.Fatalf(err.Error())
}
// We should close the database when it's no longer in use.
defer sess.Close()
// Getting a pointer to the "artist" collection.
artist, err := sess.Collection("artist")
if err != nil {
t.Fatalf(err.Error())
}
// Appending a map.
id, err = artist.Append(map[string]string{
"name": "Ozzie",
})
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Appending a struct.
id, err = artist.Append(struct {
Name string `field:name`
}{
"Flea",
})
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Appending a struct (using tags to specify the field name).
id, err = artist.Append(struct {
ArtistName string `field:"name"`
}{
"Slash",
})
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
}
示例3: ActivityJSONHandler
func ActivityJSONHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
dataRenderer := data.FromContext(ctx)
page := int(to.Int64(r.FormValue("page")))
if page <= 0 {
page = 1
}
limit := int(to.Int64(r.FormValue("limit")))
if limit <= 0 {
limit = 50
}
var cnt int
if err := models.DB.Model(&models.ListActivity{}).Count(&cnt).Error; err != nil {
panic(err)
}
totalpages := cnt / 50
if cnt%50 != 0 {
totalpages++
}
if page > totalpages {
page = totalpages
}
var activities []models.ListActivity
if err := models.DB.Limit(limit).Offset((page - 1) * limit).Order("created_at desc").Find(&activities).Error; err != nil && err != gorm.ErrRecordNotFound {
panic(err)
}
// render a better karma view
var rendered []*activityJSON
for _, v := range activities {
// load the username...
rendered = append(rendered, &activityJSON{
ListId: v.ListID,
User: models.FindUserByID(v.UserID).Username,
Comment: string(bluemonday.UGCPolicy().SanitizeBytes(blackfriday.MarkdownCommon([]byte(v.Activity)))),
Time: v.CreatedAt,
URL: render.ConvertURL("/b/" + to.String(v.ListID)),
})
}
dataRenderer.Data = map[string]interface{}{
"totalpages": totalpages,
"page": page,
"activities": rendered,
}
dataRenderer.Type = data.DataJSON
}
示例4: Count
/*
Returns the number of rows in the current table that match certain conditions.
*/
func (self *Table) Count(terms ...interface{}) (int, error) {
terms = append(terms, db.Fields{"COUNT(1) AS _total"})
result, err := self.FindAll(terms...)
if err == nil {
return int(to.Int64(result[0]["_total"])), nil
}
return 0, err
}
示例5: APIRequest
func (k *Karma) APIRequest(user *models.User, action string, value string) (interface{}, error) {
// action == label
// value == -1/0/+1/etc
// check if we have the action available
for _, v := range k.Labels {
if v.Label != action {
continue
}
// check if we can take action on this label
votable := k.checkLabel(v)
if votable&karmaCanVote == 0 {
return nil, ErrKarmaLabelIsClosed
}
if value == KarmaAccept {
if votable&karmaCanAccept == 0 {
return nil, ErrKarmaLabelCannotClose
}
k.State[v.Label] = KarmaStateAccepted
return karmaGenericOk, nil
} else if value == KarmaReject {
if votable&karmaCanReject == 0 {
return nil, ErrKarmaLabelCannotClose
}
k.State[v.Label] = KarmaStateRejected
return karmaGenericOk, nil
}
vote := to.Int64(value)
if vote < v.LowValue || vote > v.HighValue {
return nil, ErrKarmaValueOutOfRange
}
// alright, add it in
labelVotes, ok := k.Votes[v.Label]
if !ok {
labelVotes = map[string]int64{}
k.Votes[v.Label] = labelVotes
}
labelVotes[user.Username] = vote
k.save()
return karmaGenericOk, nil
}
return nil, ErrKarmaLabelNotFound
}
示例6: decodeTime
func decodeTime(node *xmlx.Node) (t Time) {
if node == nil {
return t
}
t.Type = TimeType(strings.ToUpper(node.As("*", "type")))
lowNode := Nget(node, "low")
if lowNode != nil && !lowNode.HasAttr("*", "nullFlavor") {
t.Low, _ = ParseHL7Time(lowNode.As("*", "value"))
}
highNode := Nget(node, "high")
if highNode != nil && !highNode.HasAttr("*", "nullFlavor") {
t.High, _ = ParseHL7Time(highNode.As("*", "value"))
}
val := node.As("*", "value")
if len(val) > 0 {
t.Value, _ = ParseHL7Time(val)
} else {
centerNode := Nget(node, "center")
if centerNode != nil {
t.Value, _ = ParseHL7Time(centerNode.As("*", "value"))
}
}
if t.Value.IsZero() && !t.Low.IsZero() && t.High.IsZero() {
t.Value = t.Low
}
period := Nget(node, "period")
if period != nil {
value := time.Duration(to.Int64(period.As("*", "value")))
unit := period.As("*", "unit")
switch strings.ToLower(unit) {
case "s":
t.Period = time.Second * value
case "min":
t.Period = time.Minute * value
case "h":
t.Period = time.Hour * value
case "d":
t.Period = time.Hour * 24 * value
case "wk":
t.Period = time.Hour * 24 * 7 * value
case "mo":
t.Period = time.Hour * 24 * 30 * value
}
}
return t
}
示例7: ParseGeneric
// A generic parser for wowprofessions.com.
func ParseGeneric(s string) [][]Reagent {
allmatches := itemRe.FindAllStringSubmatch(s, -1)
var ret [][]Reagent
//ret := make([][]Reagent, len(allmatches))
for _, matches := range allmatches {
// fmt.Println(matches)
count := int(to.Int64(matches[len(matches)-2]))
if count == 0 {
count = 1
}
name := strings.Trim(matches[len(matches)-1], " ")
ret = append(ret, []Reagent{Reagent{name, count}})
}
return ret
}
示例8: getHandler
// getHandler service returns a request body.
func getHandler(wri http.ResponseWriter, req *http.Request) {
var err error
var response getResponse
if err = req.ParseForm(); err != nil {
log.Printf("ParseForm: %q", err)
return
}
response.ID = uint(to.Int64(req.Form.Get("id")))
res := col.Find(response)
res.Select(
"id",
"method",
"origin",
"content_type",
"content_length",
"status",
"host",
"url",
"scheme",
"header",
"request_header",
"date_start",
"date_end",
"time_taken",
)
if err = res.One(&response.Response); err != nil {
log.Printf("res.One: %q", err)
return
}
replyJSON(wri, response)
return
}
示例9: getHandler
// getHandler service returns a request body.
func getHandler(w http.ResponseWriter, r *http.Request) {
var err error
if err = r.ParseForm(); err != nil {
log.Printf("ParseForm: %q", err)
replyCode(w, http.StatusInternalServerError)
return
}
var response getResponse
response.ID = uint(to.Int64(r.Form.Get("id")))
res := storage.Find(response.ID)
res.Select(
"id",
"method",
"origin",
"content_type",
"content_length",
"status",
"host",
"url",
"scheme",
"header",
"request_header",
"date_start",
"date_end",
"time_taken",
)
if err = res.One(&response.Response); err != nil {
log.Printf("res.One: %q", err)
replyCode(w, http.StatusInternalServerError)
return
}
replyJSON(w, response)
}
示例10: Execute
// Execute runs a luminos server using a settings file.
func (c *runCommand) Execute() (err error) {
var stat os.FileInfo
// If no settings file was specified, use the default.
if *flagSettings == "" {
*flagSettings = envSettingsFile
}
// Attempt to stat the settings file.
stat, err = os.Stat(*flagSettings)
// It must not return an error.
if err != nil {
return fmt.Errorf("Error while opening %s: %q", *flagSettings, err)
}
// We must have a value in stat.
if stat == nil {
return fmt.Errorf("Could not load settings file: %s.", *flagSettings)
}
// And the file must not be a directory.
if stat.IsDir() {
return fmt.Errorf("Could not open %s: it's a directory!", *flagSettings)
}
// Now that we're positively sure that we have a valid file, let's try to
// read settings from it.
if settings, err = loadSettings(*flagSettings); err != nil {
return fmt.Errorf("Error while reading settings file %s: %q", *flagSettings, err)
}
// Starting settings watcher.
if err = settingsWatcher(); err == nil {
watch.Watch(*flagSettings)
}
// Reading setttings.
serverType := to.String(settings.Get("server", "type"))
domain := envServerDomain
address := to.String(settings.Get("server", "socket"))
if address == "" {
domain = envServerProtocol
address = fmt.Sprintf("%s:%d", to.String(settings.Get("server", "bind")), to.Int64(settings.Get("server", "port")))
}
// Creating a network listener.
var listener net.Listener
if listener, err = net.Listen(domain, address); err != nil {
return fmt.Errorf("Could not create network listener: %q", err)
}
// Listener must be closed when the function exits.
defer listener.Close()
// Attempt to start a server.
switch serverType {
case "fastcgi":
if err == nil {
log.Printf("Starting FastCGI server. Listening at %s.\n", address)
fcgi.Serve(listener, &server{})
} else {
return fmt.Errorf("Failed to start FastCGI server: %q", err)
}
case "standalone":
if err == nil {
log.Printf("Starting HTTP server. Listening at %s.\n", address)
http.Serve(listener, &server{})
} else {
return fmt.Errorf("Failed to start HTTP server: %q", err)
}
default:
return fmt.Errorf("Unknown server type: %s", serverType)
}
return nil
}
示例11: downloadHandler
// downloadHandler provides a downloadable document given its ID.
func downloadHandler(wri http.ResponseWriter, req *http.Request) {
var err error
var response getResponse
if err = req.ParseForm(); err != nil {
log.Printf("ParseForm: %q", err)
return
}
wireFormat := to.Bool(req.Form.Get("wire"))
direction := req.Form.Get("type")
response.ID = uint(to.Int64(req.Form.Get("id")))
res := col.Find(response)
res.Select(
"id",
"url",
"method",
"header",
"request_header",
"date_end",
db.Raw{"hex(body) AS body"},
db.Raw{"hex(request_body) AS request_body"},
)
if err = res.One(&response.Response); err != nil {
log.Printf("res.One: %q", err)
return
}
var u *url.URL
if u, err = url.Parse(response.URL); err != nil {
log.Printf("url.Parse: %q", err)
return
}
var body []byte
basename := path.Base(u.Path)
switch direction {
case directionRequest:
if body, err = hex.DecodeString(string(response.RequestBody)); err != nil {
log.Printf("url.Parse: %q", err)
return
}
if wireFormat {
buf := bytes.NewBuffer(nil)
buf.WriteString(fmt.Sprintf("%s %s HTTP/1.1\r\n", response.Method, u.RequestURI()))
for k, vv := range response.RequestHeader.Header {
for _, v := range vv {
buf.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
}
}
buf.WriteString("\r\n")
wri.Header().Set("Content-Disposition", `attachment; filename="`+u.Host+"-"+basename+`.bin"`)
buf.Write(body)
http.ServeContent(wri, req, "", response.DateEnd, bytes.NewReader(buf.Bytes()))
} else {
wri.Header().Set("Content-Disposition", `attachment; filename="`+basename+`"`)
http.ServeContent(wri, req, basename, response.DateEnd, bytes.NewReader(body))
}
default:
if body, err = hex.DecodeString(string(response.Body)); err != nil {
log.Printf("url.Parse: %q", err)
return
}
if wireFormat {
buf := bytes.NewBuffer(nil)
for k, vv := range response.Header.Header {
for _, v := range vv {
buf.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
}
}
buf.WriteString("\r\n")
wri.Header().Set("Content-Disposition", `attachment; filename="`+u.Host+"-"+basename+`.bin"`)
//.........這裏部分代碼省略.........
示例12: TestResultFetch
// This test uses and result and tries to fetch items one by one.
func TestResultFetch(t *testing.T) {
var err error
var res db.Result
// Opening database.
sess, err := db.Open(wrapperName, settings)
if err != nil {
t.Fatalf(err.Error())
}
// We should close the database when it's no longer in use.
defer sess.Close()
artist, err := sess.Collection("artist")
if err != nil {
t.Fatalf(err.Error())
}
// Testing map
res = artist.Find()
row_m := map[string]interface{}{}
for {
err = res.Next(&row_m)
if err == db.ErrNoMoreRows {
// No more row_ms left.
break
}
if err == nil {
if to.Int64(row_m["id"]) == 0 {
t.Fatalf("Expecting a not null ID.")
}
if to.String(row_m["name"]) == "" {
t.Fatalf("Expecting a name.")
}
} else {
t.Fatalf(err.Error())
}
}
res.Close()
// Testing struct
row_s := struct {
Id uint64
Name string
}{}
res = artist.Find()
for {
err = res.Next(&row_s)
if err == db.ErrNoMoreRows {
// No more row_s' left.
break
}
if err == nil {
if row_s.Id == 0 {
t.Fatalf("Expecting a not null ID.")
}
if row_s.Name == "" {
t.Fatalf("Expecting a name.")
}
} else {
t.Fatalf(err.Error())
}
}
res.Close()
// Testing tagged struct
row_t := struct {
Value1 uint64 `field:"id"`
Value2 string `field:"name"`
}{}
res = artist.Find()
for {
err = res.Next(&row_t)
if err == db.ErrNoMoreRows {
// No more row_t's left.
break
}
if err == nil {
if row_t.Value1 == 0 {
t.Fatalf("Expecting a not null ID.")
}
if row_t.Value2 == "" {
//.........這裏部分代碼省略.........
示例13: Append
// Appends an item (map or struct) into the collection.
func (t *table) Append(item interface{}) (interface{}, error) {
var pKey []string
var columns sqlgen.Columns
var values sqlgen.Values
var arguments []interface{}
//var id []interface{}
cols, vals, err := t.FieldValues(item, toInternal)
if err != nil {
return nil, err
}
columns = make(sqlgen.Columns, 0, len(cols))
for i := range cols {
columns = append(columns, sqlgen.Column{cols[i]})
}
arguments = make([]interface{}, 0, len(vals))
values = make(sqlgen.Values, 0, len(vals))
for i := range vals {
switch v := vals[i].(type) {
case sqlgen.Value:
// Adding value.
values = append(values, v)
default:
// Adding both value and placeholder.
values = append(values, sqlPlaceholder)
arguments = append(arguments, v)
}
}
if pKey, err = t.source.getPrimaryKey(t.tableN(0)); err != nil {
if err != sql.ErrNoRows {
// Can't tell primary key.
return nil, err
}
}
stmt := sqlgen.Statement{
Type: sqlgen.SqlInsert,
Table: sqlgen.Table{t.tableN(0)},
Columns: columns,
Values: values,
}
// No primary keys defined.
if len(pKey) == 0 {
var res sql.Result
if res, err = t.source.doExec(stmt, arguments...); err != nil {
return nil, err
}
// Attempt to use LastInsertId() (probably won't work, but the exec()
// succeeded, so the error from LastInsertId() is ignored).
lastID, _ := res.LastInsertId()
return lastID, nil
}
var rows *sql.Rows
// A primary key was found.
stmt.Extra = sqlgen.Extra(fmt.Sprintf(`RETURNING "%s"`, strings.Join(pKey, `", "`)))
if rows, err = t.source.doQuery(stmt, arguments...); err != nil {
return nil, err
}
defer rows.Close()
var keyMap map[string]interface{}
err = sqlutil.FetchRow(rows, &keyMap)
// Does the item satisfy the db.IDSetter interface?
if setter, ok := item.(db.IDSetter); ok {
if err := setter.SetID(keyMap); err != nil {
return nil, err
}
return nil, nil
}
// The IDSetter interface does not match, we'll be looking for another
// interface match.
if len(keyMap) == 1 {
id := keyMap[pKey[0]]
// Matches db.Int64IDSetter
if setter, ok := item.(db.Int64IDSetter); ok {
if err = setter.SetID(to.Int64(id)); err != nil {
return nil, err
}
return nil, nil
}
// Matches db.Uint64IDSetter
if setter, ok := item.(db.Uint64IDSetter); ok {
//.........這裏部分代碼省略.........
示例14: Execute
func (self *runCommand) Execute() error {
// Default settings file.
if *flagSettings == "" {
*flagSettings = DEFAULT_SETTINGS_FILE
}
stat, err := os.Stat(*flagSettings)
if err != nil {
return fmt.Errorf("Error while opening %s: %s", *flagSettings, err.Error())
}
if stat != nil {
if stat.IsDir() == true {
return fmt.Errorf("Could not open %s: it's a directory!", *flagSettings)
} else {
settings, err = loadSettings(*flagSettings)
if err != nil {
return fmt.Errorf("Error while reading settings file %s: %s", *flagSettings, err.Error())
}
err = settingsWatcher()
if err == nil {
watch.Watch(*flagSettings)
}
serverType := to.String(settings.Get("server", "type"))
domain := DEFAULT_SERVER_DOMAIN
address := to.String(settings.Get("server", "socket"))
if address == "" {
domain = DEFAULT_SERVER_PROTOCOL
address = fmt.Sprintf("%s:%d", to.String(settings.Get("server", "bind")), to.Int64(settings.Get("server", "port")))
}
listener, err := net.Listen(domain, address)
if err != nil {
return err
}
defer listener.Close()
switch serverType {
case "fastcgi":
if err == nil {
log.Printf("Starting FastCGI server. Listening at %s.", address)
fcgi.Serve(listener, &server{})
} else {
return fmt.Errorf("Failed to start FastCGI server: %s", err.Error())
}
case "standalone":
if err == nil {
log.Printf("Starting HTTP server. Listening at %s.", address)
http.Serve(listener, &server{})
} else {
return fmt.Errorf("Failed to start HTTP server: %s", err.Error())
}
default:
return fmt.Errorf("Unknown server type: %s", serverType)
}
}
} else {
return fmt.Errorf("Could not load settings file: %s.", *flagSettings)
}
return nil
}
示例15: ListsAPIHandler
// ListsAPIHandler shows the collection of lists, with filters, paginated, JSON'ified.
func ListsAPIHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
dataRenderer := data.FromContext(ctx)
dataRenderer.Type = data.DataJSON
platform := r.FormValue("platform")
channel := r.FormValue("channel")
status := r.FormValue("status")
limit := int(to.Int64(r.FormValue("limit")))
if limit <= 0 {
limit = 50 // reasonable
}
page := int(to.Int64(r.FormValue("page")))
if page <= 0 {
page = 1
}
baseDB := models.DB.Model(&models.List{})
if platform != "" {
baseDB = baseDB.Where("platform = ?", platform)
}
if channel != "" {
baseDB = baseDB.Where("channel = ?", channel)
}
if status == models.ListRunning || status == models.ListPending || status == models.ListSuccess || status == models.ListFailed {
baseDB = baseDB.Where("stage_result = ?", status)
} else if status != "" {
panic(ErrBadRequest)
}
var cnt int
if err := baseDB.Count(&cnt).Error; err != nil {
panic(err)
}
totalpages := cnt / limit
if cnt%limit != 0 {
totalpages++
}
if page > totalpages {
page = totalpages
}
var packages []*models.List
if err := baseDB.Limit(limit).Offset((page - 1) * limit).Order("updated_at desc").Find(&packages).Error; err != nil && err != gorm.ErrRecordNotFound {
panic(err)
}
dataRenderer.Data = map[string]interface{}{
"lists": packages,
"pages": map[string]interface{}{
"prev": page - 1,
"current": page,
"next": page + 1,
"total": totalpages,
},
}
}