标签: go

为什么浮点文字和变量在Go中给出不同的结果?

在下面的简单的计算,cd结束了不同的值(它们是关闭的单个位).这是为什么?

a := 4000.0
b := 1e-9
c := a / b
d := 4000.0 / 1e-9
Run Code Online (Sandbox Code Playgroud)

go

3
推荐指数
1
解决办法
194
查看次数

Golang反思改进

有人知道更好的方法吗?目标是将自定义定义的字段再次从字符串转换回其int类型.

switch val.Kind() {
    case reflect.Int:
            intID, err := strconv.ParseInt(id, 10, 0)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int(intID)))

    case reflect.Int8:
            intID, err := strconv.ParseInt(id, 10, 8)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int8(intID)))

    case reflect.Int16:
            intID, err := strconv.ParseInt(id, 10, 16)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int16(intID)))

    case reflect.Int32:
            intID, err := strconv.ParseInt(id, 10, 32)
            if err != nil {
                    return err
            }
            val.Set(reflect.ValueOf(int32(intID)))

    case reflect.Int64:
            intID, err := strconv.ParseInt(id, 10, 64) …
Run Code Online (Sandbox Code Playgroud)

reflection go

3
推荐指数
1
解决办法
139
查看次数

Golang Goji:如何同时提供静态内容和api

过去两周我一直在玩Golang,最后可以开始真正的应用程序.它使用NGINX提供的静态HTML文件,API使用Goji Web Framework作为后端.我不使用任何Golang模板,因为一切都是Angular.Js,所以静态可以满足我的需求.

我想选择是否在生产中使用NGINX,或者让Go使用应用程序使用的相同端口在root上提供静态内容(8000).这样开发环境就不需要安装NGINX.

所以,尝试像这样添加一个默认多路复用器的句柄

goji.DefaultMux.Handle("/*", serveStatic)

func serveStatic(w http.ResponseWriter, r *http.Request) {
//http.ServeFile(w, r, r.URL.Path[1:])
//http.FileServer(http.Dir("static"))
http.StripPrefix("/static/", http.FileServer(http.Dir("static")))
Run Code Online (Sandbox Code Playgroud)

}

在所有API路径都已注册之后执行此句柄(否则API将无效).

我已经尝试过任何类型的组合,它可以将我重定向到HTTP 404,或者将HTML内容显示为文本.两者都不好.我想知道是否有人来过这里,可以让我了解我做错了什么.

谢谢.

虽然这与我的问题无关,但这里是我正在使用的NGINX配置:

server {
listen 80;

# enable gzip compression
    gzip on;
    gzip_min_length  1100;
    gzip_buffers  4 32k;
    gzip_types    text/plain application/x-javascript text/xml text/css;
    gzip_vary on;
# end gzip configuration

location / {
    root /home/mleyzaola/go/src/bitbucket.org/mauleyzaola/goerp/static;
    try_files $uri $uri/ /index.html = 404;
}

location /api {
    proxy_pass http://localhost:8000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass …
Run Code Online (Sandbox Code Playgroud)

go goji

3
推荐指数
1
解决办法
4427
查看次数

当我在golang中查询mongodb时,如何获得UTC时间

我对Golang和MongoDB相对较新,遇到了一个日期问题,我似乎可以在MongoDB中插入一个UTC日期,但是当我通过Golang查询时,它会自动转换为本地时间.我希望在没有转换的情况下从UTC的MongoDB中恢复.这是一个简单的例子:

type SampleItem struct {
    ObjId      bson.ObjectId `bson:"_id,omitempty" json:"-"`
    SampleDate time.Time     `bson:"sampleDate" json:"sampleDate"`
}

func TestMe() {

    var item SampleItem
    var items []SampleItem

    sess := getSession()
    defer sess.Close()

    item.SampleDate = time.Now().UTC()
    fmt.Printf("%s\n", item.SampleDate)

    collection := sess.DB("myCollection").C("sampleItems")
    collection.Insert(item)

    err := collection.Find(bson.M{}).All(&items)
    if err == nil {
        fmt.Printf("%s\n", items[0].SampleDate)
    }
}
Run Code Online (Sandbox Code Playgroud)

我的输出:

2014-10-12 04:10:50.3992076 +0000 UTC

2014-10-11 23:10:50.399 -0500 CDT

似乎mgo驱动程序可能会自动转换它,因为当我从控制台窗口查询mongodb时,我的日期是UTC.我错过了某个地方的mgo选项吗?

go mongodb mgo

3
推荐指数
1
解决办法
3248
查看次数

Golang构建约束随机

我在头文件中有两个具有不同构建约束的go文件.

constants_production.go:

// +build production,!staging

package main

const (
  URL               = "production"
)
Run Code Online (Sandbox Code Playgroud)

constants_staging.go:

// +build staging,!production

package main

const (
  URL               = "staging"
)
Run Code Online (Sandbox Code Playgroud)

main.go:

package main

func main() {
  fmt.Println(URL)
}
Run Code Online (Sandbox Code Playgroud)

当我做的时候go install -tags "staging",有时会打印production; 有时,它打印staging.同样,当我这样做的时候go install -tags "production"......

如何在每次构建时获得一致的输出?当我将staging指定为构建标志时,如何使其进行打印分段?当我将生产指定为构建标志时,如何使其打印生产?我在这里做错了吗?

compilation build go

3
推荐指数
1
解决办法
519
查看次数

Go的精确GC如何工作?

Go 1.3实现了精确的垃圾收集器.

它如何精确识别指针?

memory garbage-collection go

3
推荐指数
1
解决办法
582
查看次数

fmt.Scan在Go中无法正常工作

我正在尝试一个应该测试fmt.Scanf的片段,但它似乎没有按预期工作:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("What is your favorite color?")
    var favoriteColor string
    fmt.Scanf("%s", &favoriteColor)
    fmt.Println("Fave color is", favoriteColor)
    fmt.Println("What is your favorite food?")
    var myfood string
    fmt.Scanf("%s", &myfood)
    fmt.Printf("I like %s too!\n", myfood)
    fmt.Printf("Wait two seconds please...\n")
    time.Sleep(2000 * time.Millisecond)
    fmt.Printf("Your favorite color is %s, and the food you like best is %q\n", favoriteColor, myfood)
}
Run Code Online (Sandbox Code Playgroud)

然而,只有第一个答案,程序继续到最后,然后返回:

What is your favorite color?
red
Fave color is red
What is your favorite food?
I …
Run Code Online (Sandbox Code Playgroud)

scanf go

3
推荐指数
1
解决办法
929
查看次数

Golang RESTful API负载测试导致数据库连接过多

我认为我在Golang中管理数据库连接池存在严重问题.我使用Gorilla Web工具包构建了一个RESTful API,当只有少量请求被发送到服务器时,它工作得很好.但是现在我开始使用loader.io站点进行负载测试.我为这篇长篇文章道歉,但我想给你全面的了解.

在进一步讨论之前,以下是运行API和MySQL的服务器的一些信息:专用主机Linux 8GB RAM Go版本1.1.1使用go-sql-driver MySQL 5.1进行数据库连接

使用loader.io我可以发送1000 GET请求/ 15秒没有问题.但是当我发送1000个POST请求/ 15秒时,我会收到很多错误,所有这些错误都是ERROR 1040太多的数据库连接.许多人在网上报道了类似的问题.请注意,我现在只测试一个特定的POST请求.对于这篇帖子请求,我确保了以下内容(许多其他人也在线提出)

  1. 我确保我不使用Open和Close*sql.DB来实现短暂的功能.所以我在连接池中只创建了全局变量,如下面的代码所示,尽管我在这里建议是因为我不喜欢使用全局变量.

  2. 我确保尽可能使用db.Exec,并且只在预期结果时使用db.Query和db.QueryRow.

由于上面没有解决我的问题,我尝试设置db.SetMaxIdleConns(1000),解决了1000个POST请求/ 15秒的问题.意思是不再有1040个错误.然后我将负载增加到2000 POST请求/ 15秒,然后我又开始获得ERROR 1040.我试图增加db.SetMaxIdleConns()中的值,但这没有什么区别.

我通过运行SHOW STATUS WHERE variable_name='Threads_connected'来获取MySQL数据库中连接数的一些连接统计信息;

对于1000个POST请求/ 15秒:观察到#threads_connected~ = 100对于2000个POST请求/ 15秒:观察到#threads_connected~ = 600

我还增加了my.cnf中MySQL的最大连接数,但这并没有什么区别.你有什么建议?代码看起来不错吗?如果是,那么可能连接只是有限的.

您将在下面找到该代码的简化版本.

var db *sql.DB

func main() {
    db = DbConnect()
    db.SetMaxIdleConns(1000)

    http.Handle("/", r)
    err := http.ListenAndServe(fmt.Sprintf("%s:%s", API_HOST, API_PORT), nil)

    if err != nil {
       fmt.Println(err)
    }
}

func DbConnect() *sql.DB {
    db, err := sql.Open("mysql", connectionString)
    if err != nil {
        fmt.Printf("Connection error: %s\n", err.Error())
        return …
Run Code Online (Sandbox Code Playgroud)

mysql sql go gorilla

3
推荐指数
1
解决办法
3489
查看次数

如何在Go GAE应用程序中可视化代码覆盖率信息?

我正在使用最新的 Go GAE SDK开发服务器.每次更改后我都会运行测试:

goapp test -test.v=true
Run Code Online (Sandbox Code Playgroud)

-cover用来记录覆盖范围,如下所述goapp help testflag:

goapp test -cover -test.v=true -test.coverprofile=c.out
[..]
coverage: 53.8% of statements
ok      _/var/lib/jenkins/jobs/loyalty/workspace    30.464s
Run Code Online (Sandbox Code Playgroud)

这成功完成并打印测试所涵盖的行的百分比.但是,尝试可视化结果失败:

goapp tool cover -html=c.out
cover: can't find "app.go": cannot find package "_/home/ingo/git/loyalty/" in any of:
/home/ingo/Downloads/go_appengine_sdk_linux_amd64-1.9.10/go_appengine/goroot/src/pkg/_/home/ingo/git/loyalty (from $GOROOT)
/home/ingo/git/loyalty/src/_/home/ingo/git/loyalty (from $GOPATH)
Run Code Online (Sandbox Code Playgroud)

Go的封面工具是否仅适用于非GAE应用程序?我是否必须以不同方式打包我的应用程序才能显示覆盖率结果?

我以前在golang-nuts上问过这个问题是不成功的.

tdd google-app-engine unit-testing code-coverage go

3
推荐指数
1
解决办法
402
查看次数

使用Go解析XML,使用小写的多个元素

我不知道如何使这段代码工作.我只是想解析一个像这样的简单XML文件:

package main

import (
    "encoding/xml"
    "fmt"
)

type Data struct {
    XMLName xml.Name `xml:"data"`
    Nam     string   `xml:"nam,attr"`
}

type Struct struct {
    XMLName xml.Name `xml:"struct"`
    Data    []Data
}

func main() {

    x := `  
        <struct>
            <data nam="MESSAGE_TYPE">     
            </data>
            <data nam="MESSAGE_TYPE2">
            </data>
        </struct>
    `
    s := Struct{}
    err := xml.Unmarshal([]byte(x), &s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", s)
    fmt.Println(s.Data)
}
Run Code Online (Sandbox Code Playgroud)

我得到的是:

{{ struct} []}
[]
Run Code Online (Sandbox Code Playgroud)

但是,当我将"data"元素更改为大写时,如下所示:

package main

import (
    "encoding/xml"
    "fmt"
)

type Data struct {
    XMLName …
Run Code Online (Sandbox Code Playgroud)

xml go

3
推荐指数
1
解决办法
1207
查看次数