使用Go在Google App Engine中读取本地文件

时间:2011-08-04 23:41:35

标签: google-app-engine go

我正试图在谷歌应用引擎上使用go代替python我的网站。但是当我在本地测试时,我的脚本一直出现这个错误。

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

我很困惑,但如果我发表评论

,它会毫无错误地运行
channel <- buffer[0:dat]

所以我必须错误地使用频道,任何帮助?

编辑:

这是工作代码,非常感谢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)
}

1 个答案:

答案 0 :(得分:5)

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

BTW:如果使用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:])
}