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

sev*_*bar 3 google-app-engine go

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

panic: runtime error: invalid memory address or nil pointer dereference
Run Code Online (Sandbox Code Playgroud)

我很困惑,但如果我发表评论,它会毫无错误地运行

channel <- buffer[0:dat]
Run Code Online (Sandbox Code Playgroud)

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

编辑:

这是工作代码,非常感谢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)
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你的程序有时会引起恐慌的原因是它有时会w http.ResponseWriter在程序退出load函数后写入.该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:])
}
Run Code Online (Sandbox Code Playgroud)