douzhanlai4671
2018-12-16 13:39 阅读 201
已采纳

Go中的'net / http'中的request.FormValue为空

I'm trying to create a simple http service with the endpoint to download file to the local system in Go. The link comes in ?uri tag, but when I want to get it I receive an empty string. I tried to parse the form of my request but it didn't help. Here is my code:

func main() {
http.HandleFunc("/download", DownloadHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

func DownloadHandler(writer http.ResponseWriter, request *http.Request) {
    prsErr := request.ParseForm()
    if prsErr != nil{
        panic(prsErr)
    }
    uri := request.FormValue("?uri")
    _, _ = writer.Write([]byte(uri))
    err := DownloadFile("img.png", uri)
    if err != nil {
        panic(err)
    }
}

func DownloadFile(filepath string, url string) error {

    // Create the file
    out, err := os.Create(filepath)
    if err != nil {
        return err
    }
    defer out.Close()

    // Get the data
    resp, err := http.Get(url)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    // Write the body to file
    _, err = io.Copy(out, resp.Body)
    if err != nil {
        return err
    }

    return nil
}

I will appreciate any help! Thank you!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dsgw8802 dsgw8802 2018-12-16 13:43

    invalid at request.FormValue("?uri")

    uri := request.FormValue("uri")
    
    点赞 评论 复制链接分享

相关推荐