dqwh1201 2019-03-18 09:31
浏览 58

无法在golang网络应用中重定向。 坚持一页

This is code snippet from a file called upload.go. I tried a lot of ways to redirect to another pages. I want to redirect to another page when the statements in POST are completed running.

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "text/template"
)

func upload(w http.ResponseWriter, r *http.Request) {

    if r.Method == "GET" {
        // GET
        t, _ := template.ParseFiles("upload.gtpl")

        t.Execute(w, nil)

    } else if r.Method == "POST" {
        // Post
        file, handler, err := r.FormFile("uploadfile")
        if err != nil {
            fmt.Println(err)
            return
        }
        defer file.Close()

        fmt.Fprintf(w, "%v", handler.Header)
        f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
        if err != nil {
            fmt.Println(err)
            return
        }
        defer f.Close()

        io.Copy(f, file)

        img, err := imgio.Open("./test/" + handler.Filename)
        if err != nil {
            panic(err)
        }

        inverted := effect.Invert(img)
        if err := imgio.Save("filename.png", inverted, imgio.PNGEncoder()); err != nil {
            panic(err)
        }

        fmt.Fprintf(w, "%v", handler.Header)
        http.Redirect(w, r, "www.google.com", http.StatusMovedPermanently)

    } else {
        fmt.Println("Unknown HTTP " + r.Method + "  Method")
    }
}

func main() {
    http.HandleFunc("/upload", upload)
    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hi")
        http.Redirect(w, r, "www.google.com", http.StatusMovedPermanently)
    })

    http.ListenAndServe(":9090", nil) // setting listening port
}

It stays on the upload page what ever I do. Can anyone help me debug this?

  • 写回答

1条回答 默认 最新

  • duanjian4150 2019-03-18 17:25
    关注

    Your code is writing to the ResponseWriter before trying to send a redirect.

    Upon the first write to the ResponseWriter, the status code (200 OK) and headers are sent, if they haven't already been sent, and then the data you passed to the writer.

    If you intend to send an HTTP redirect, you can't write any response body to the ResponseWriter. From reading your code, it doesn't make much sense why you are writing to it in the first place. They look like debugging print statements, which you probably ought to send to os.Stderr or a logger instead of the web page response body.

    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现