gpt4 book ai didi

google-app-engine - 使用 Go 在 Google App Engine 中读取本地文件

转载 作者:IT王子 更新时间:2023-10-29 01:00:47 26 4
gpt4 key购买 nike

我正在尝试在 Google App Engine 上为我的网站使用 go 而不是 python。但是当我在本地测试时,我的脚本总是出现这个错误。

panic: runtime error: invalid memory address or nil pointer dereference

我很困惑,但是如果我注释掉它会正常运行

channel <- buffer[0:dat]

所以我一定是错误地使用了 channel ,有什么帮助吗?

编辑:

这是工作代码,非常感谢 Kevin Ballard 帮助我获得这个代码。

package defp

import (
"fmt"
"http"
"os"
)

func getContent(filename string, channel chan []byte) {
file, err := os.OpenFile(filename, os.O_RDONLY, 0666)
defer file.Close()
if err == nil {
fmt.Printf("FILE FOUND : " + filename + " \n")
buffer := make([]byte, 16)
dat, err := file.Read(buffer)
for err == nil {
fmt.Printf("herp")
channel <- buffer[0:dat]
buffer = make([]byte, 16)
dat, err = file.Read(buffer)
}
close(channel)
fmt.Printf("DONE READING\n")
} else {
fmt.Printf("FILE NOT FOUND : " + filename + " \n")
}
}
func writeContent(w http.ResponseWriter, channel chan []byte) {
fmt.Printf("ATTEMPTING TO WRITE CONTENT\n")
go func() {
for bytes := range channel {
w.Write(bytes)
fmt.Printf("BYTES RECEIVED\n")
}
}()
fmt.Printf("FINISHED WRITING\n")
}
func load(w http.ResponseWriter, path string) {
fmt.Printf("ATTEMPTING LOAD " + path + "\n")
channel := make(chan []byte, 50)
writeContent(w, channel)
getContent(path, channel)
}
func handle(w http.ResponseWriter, r *http.Request) {
fmt.Printf("HANDLING REQUEST FOR " + r.URL.Path[1:] + "\n")
load(w, r.URL.Path[1:])
}
func init() {
http.HandleFunc("/", handle)
}

最佳答案

你的程序有时会 panic 的原因是它有时会在程序退出 load 函数后写入 w http.ResponseWriter。当程序退出处理程序函数时,http 包会自动关闭 http.ResponseWriter。在函数 writeContent 中,程序有时会尝试写入已关闭的 http.ResponseWriter

顺便说一句:如果您使用io.Copy 函数,您可以使程序源代码更小。

要始终获得可预测的行为,请确保您希望程序为响应 HTTP 请求而执行的所有工作在退出处理函数之前完成。例如:

func writeContent(w http.ResponseWriter, channel chan []byte) {
fmt.Printf("ATTEMPTING TO WRITE CONTENT\n")
for bytes := range channel {
w.Write(bytes)
fmt.Printf("BYTES RECEIVED\n")
}
fmt.Printf("FINISHED WRITING\n")
}

func load(w http.ResponseWriter, path string) {
fmt.Printf("ATTEMPTING LOAD " + path + "\n")
channel := make(chan []byte)
workDone := make(chan byte)
go func() {
writeContent(w, channel)
workDone <- 1 //Send an arbitrary value
}()
go func() {
getContent(path, channel)
workDone <- 2 //Send an arbitrary value
}()
<-workDone
<-workDone
}

func handle(w http.ResponseWriter, r *http.Request) {
fmt.Printf("HANDLING REQUEST FOR " + r.URL.Path[1:] + "\n")
load(w, r.URL.Path[1:])
}

关于google-app-engine - 使用 Go 在 Google App Engine 中读取本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6949899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com