运行我的 Go 程序时,它会发生 panic 并返回以下内容:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x38 pc=0x26df]
goroutine 1 [running]:
main.getBody(0x1cdcd4, 0xf800000004, 0x1f2b44, 0x23, 0xf84005c800, ...)
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:65 +0x2bb
main.getToken(0xf84005c7e0, 0x10)
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:140 +0x156
main.main()
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:178 +0x61
goroutine 2 [syscall]:
created by runtime.main
/usr/local/Cellar/go/1.0.3/src/pkg/runtime/proc.c:221
goroutine 3 [syscall]:
syscall.Syscall6()
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/asm_darwin_amd64.s:38 +0x5
syscall.kevent(0x6, 0x0, 0x0, 0xf840085188, 0xa, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/zsyscall_darwin_amd64.go:199 +0x88
syscall.Kevent(0xf800000006, 0x0, 0x0, 0xf840085188, 0xa0000000a, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/syscall_bsd.go:546 +0xa4
net.(*pollster).WaitFD(0xf840085180, 0xf840059040, 0x0, 0x0, 0x0, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/net/fd_darwin.go:96 +0x185
net.(*pollServer).Run(0xf840059040, 0x0)
/usr/local/Cellar/go/1.0.3/src/pkg/net/fd.go:236 +0xe4
created by net.newPollServer
/usr/local/Cellar/go/1.0.3/src/pkg/net/newpollserver.go:35 +0x382
我查看了其他人对相同异常的响应,但看不到任何简单的东西(即未处理的错误)。
我正在一台无法访问代码中列出的 API 服务器的机器上运行它,但我希望它会返回一个适当的错误(因为我试图捕获此类错误)。
package main
/*
Fido fetches the list of public images from the Glance server, captures the IDs of images with 'status': 'active' and then queues the images for pre-fetching with the Glance CLI utility `glance-cache-manage`. Once the images are added to the queue, `glance-cache-prefetcher` is called to actively fetch the queued images into the local compute nodes' image cache.
See http://docs.openstack.org/developer/glance/cache.html for further details on the Glance image cache.
*/
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
/*
"log"
"log/syslog"
*/
"net/http"
"os"
"os/exec"
)
func prefetchImages() error {
cmd := exec.Command("glance-cache-prefetcher")
err := cmd.Run()
if err != nil {
return fmt.Errorf("glance-cache-prefetcher failed to execute properly: %v", err)
}
return nil
}
func queueImages(hostname string, imageList []string) error {
for _, image := range imageList {
cmd := exec.Command("glance-cache-manage", "--host=", hostname, "queue-image", image)
err := cmd.Run()
if err != nil {
return fmt.Errorf("glance-cache-manage failed to execute properly: %v", err)
} else {
fmt.Printf("Image %s queued", image)
}
}
return nil
}
func getBody(method string, url string, headers map[string]string, body []byte) ([]byte, error) {
client := &http.Client{}
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
for key, value := range headers {
req.Header.Add(key, value)
}
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
var bodyBytes []byte
if res.StatusCode == 200 {
bodyBytes, err = ioutil.ReadAll(res.Body)
} else if err != nil {
return nil, err
} else {
return nil, fmt.Errorf("The remote end did not return a HTTP 200 (OK) response.")
}
return bodyBytes, nil
}
func getImages(authToken string) ([]string, error) {
type GlanceDetailResponse struct {
Images []struct {
Name string `json:"name"`
Status string `json:"status"`
ID string `json:"id"`
}
}
method := "GET"
url := "http://192.168.1.2:9292/v1.1/images/detail"
headers := map[string]string{"X-Auth-Token": authToken}
bodyBytes, err := getBody(method, url, headers, nil)
if err != nil {
return nil, fmt.Errorf("unable to retrieve the response body from the Glance API server: %v", err)
}
var glance GlanceDetailResponse
err = json.Unmarshal(bodyBytes, &glance)
if err != nil {
return nil, fmt.Errorf("unable to parse the JSON response:", err)
}
imageList := make([]string, 10)
for _, image := range glance.Images {
if image.Status == "active" {
imageList = append(imageList, image.ID)
}
}
return imageList, nil
}
func getToken() (string, error) {
type TokenResponse struct {
Auth []struct {
Token struct {
Expires string `json:"expires"`
ID string `json:"id"`
}
}
}
method := "POST"
url := "http://192.168.1.2:5000/v2.0/tokens"
headers := map[string]string{"Content-type": "application/json"}
creds := []byte(`{"auth":{"passwordCredentials":{"username": "glance", "password":"<password>"}, "tenantId":"<tenantkeygoeshere>"}}`)
bodyBytes, err := getBody(method, url, headers, creds)
if err != nil {
return "", err
}
var keystone TokenResponse
err = json.Unmarshal(bodyBytes, &keystone)
if err != nil {
return "", err
}
authToken := string((keystone.Auth[0].Token.ID))
return authToken, nil
}
func main() {
/*
slog, err := syslog.New(syslog.LOG_ERR, "[fido]")
if err != nil {
log.Fatalf("unable to connect to syslog: %v", err)
os.Exit(1)
} else {
defer slog.Close()
}
*/
hostname, err := os.Hostname()
if err != nil {
// slog.Err("Hostname not captured")
os.Exit(1)
}
authToken, err := getToken()
if err != nil {
// slog.Err("The authentication token from the Glance API server was not retrieved")
os.Exit(1)
}
imageList, err := getImages(authToken)
err = queueImages(hostname, imageList)
if err != nil {
// slog.Err("Could not queue the images for pre-fetching")
os.Exit(1)
}
err = prefetchImages()
if err != nil {
// slog.Err("Could not queue the images for pre-fetching")
os.Exit(1)
}
return
}
最佳答案
根据 func (*Client) Do 的文档:
"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.
When err is nil, resp always contains a non-nil resp.Body."
然后看这段代码:
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
我猜 err 不是 nil。在检查 err 之前,您正在访问 res.Body 上的 .Close() 方法。
defer 只延迟函数调用。立即访问字段和方法。
因此,请立即尝试检查错误。
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
关于Go: panic :运行时错误:无效的内存地址或零指针取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16280176/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/
ruby如何管理内存。例如:如果我们在执行过程中采用C程序,则以下是内存模型。类似于这个ruby如何处理内存。C:__________________|||stack|||------------------||||------------------|||||Heap|||||__________________|||data|__________________|text|__________________Ruby:? 最佳答案 Ruby中没有“内存”这样的东西。Class#allocate分配一个对象并返回该对象。这就是程序
我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge
我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa
GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'