Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

go - send an receive http headers in Golang

func main() {
    http.HandleFunc("/", foo)
    log.Println("Listening...")
    http.ListenAndServe(":6001", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("successfull", "A Go Web Server")

    fi := path.Join("templates/VastPlayer", "TempVide_.txt")
    tmpl, err := template.ParseFiles(fi)

    if err != nil {
        w.Header().Set("Error", err.Error())
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    if err := tmpl.Execute(w, ""); err != nil {
        w.Header().Set("Error", err.Error())
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

If I give a valide template I got "successfull" : "A Go Web Server" on the Header, but if I give no existing tempalte I got 502 Bad Gateway and this on the header

HTTP/1.1 502 Bad Gateway
Server: nginx/1.8.0
Date: Mon, 06 Jul 2015 15:19:31 GMT
Content-Type: text/html
Content-Length: 574
Connection: keep-alive

I want to know if there is a way to send the Error that I got through a header, I mean

templates/VastPlayer/TempVide_.txt: no such file or directory


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Send

w.Header().Add("Status", "200")
w.Header().Add("Body", "Book Added Successfully")

Recieve

fmt.Println("response Status:", resp.Header.Get("Status"))
fmt.Println("response Body:", resp.Header.Get("Body"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...