我需要在golang代码中进行http调用。我的服务器代码将创建http请求对象并将其放入数据库中。
工作代码将从数据库获取数据,并且应该能够使用持久请求对象进行 http 调用。
可以通过序列化http请求直接将请求对象持久化到数据库中还是需要在数据库中单独添加method/URL/body?
最佳答案
没有一个好的方法来序列化 http.Request
结构本身(请参阅下面的注释),但您可以将请求序列化回 HTTP/1.1 有线格式(也可以反序列化)。这可以使用 Request.Write
来完成和 http.ReadRequest
:
func captureRequestData(req *http.Request) error {
var b = &bytes.Buffer{} // holds serialized representation
var tmp *http.Request
var err error
if err = req.Write(b); err != nil { // serialize request to HTTP/1.1 wire format
return err
}
r := bufio.NewReader(b)
if tmp, err = http.ReadRequest(r); err != nil { // deserialize request
return err
}
*req = *tmp // replace original request structure
return nil
}
序列化缓冲区的持久性只需保存 b
的副本即可。您可能更愿意保留字符串
表示形式,这涉及一些额外的转换:
s := b.String() // persist this
r := bufio.NewReader(strings.NewReader(s))
至少有几个原因导致您不能只使用 json.Marshal()
为此:
public fields of
Request
包括 Marshall 不接受的函数:json: unsupported type: func() (io.ReadCloser, error)
Request
还包含一个私有(private)字段ctx
,它会阻止任何通用的反序列化尝试:ctx is either the client or server context. It should only be modified via copying the whole Request using WithContext. It is unexported to prevent people from using Context wrong and mutating the contexts held by callers of the same request.
关于http - 有没有办法序列化golang http请求对象并持久保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498297/