[英]How do I Marshal an entire http.Request using an encoder with GoLang?
I have a simple go server...我有一个简单的 go 服务器...
package main
import (
"net/http"
"log"
)
func simple(w http.ResponseWriter, r *http.Request){
b := []byte("Hello World")
w.Write(b)
}
func main(){
http.HandleFunc("/", index)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Now I want to print out the whole request.现在我想打印出整个请求。 I want headers, url, payload, etc. I see in Go this is typically done by using an "encoder" to "marshal" the object but when I try that...我想要标头、url、有效负载等。我在 Go 中看到,这通常是通过使用“编码器”来“编组”object 来完成的,但是当我尝试这样做时……
import (
"net/http"
"log"
"encoding/json"
)
func simple(w http.ResponseWriter, r *http.Request){
e, err := json.Marshal(r)
if(err != nil){
log.Fatal(err)
}
w.Write(e)
}
with the request object I get...请求 object 我得到...
json: unsupported type: func() (io.ReadCloser, error)
Again this makes sense to me because, although I am new to go, I can understand that this is a function that returns a stream. My question is what do I need to use to get EVERYTHING in the request including headers (SERVER COOKIES).这对我来说再次有意义,因为虽然我是 go 的新手,但我可以理解这是一个返回 stream 的 function。我的问题是我需要使用什么来获取请求中的所有内容,包括标头 (SERVER COOKIES)。 I know I can write a custom Marshaler but I would like to avoid that.我知道我可以编写自定义封送拆收器,但我想避免这种情况。
Is there a simple way to marshal an entire http request in go?有没有一种简单的方法可以在 go 中编组整个 http 请求?
If you're interested in the body and the headers, you can get them this way:如果您对正文和标题感兴趣,可以通过以下方式获取它们:
package main
import (
"fmt"
"net/http"
"strings"
"io/ioutil"
)
func main() {
body := `{"foo": "bar"}`
req, _ := http.NewRequest(http.MethodPost, "http://my.url", strings.NewReader(body))
req.Header.Add("my-header-key", "my-header-value")
req.AddCookie(&http.Cookie{Name: "my-cookie", Value: "cookie-value"})
fmt.Println("body:")
reqBody, _ := req.GetBody()
readReqBody, _ := ioutil.ReadAll(reqBody)
fmt.Println(string(readReqBody))
fmt.Println()
fmt.Println("cookies:")
for name, value := range req.Header {
fmt.Println(name, value)
}
}
This should print this:这应该打印这个:
body:
{"foo": "bar"}
cookies:
My-Header-Key [my-header-value]
Cookie [my-cookie=cookie-value]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.