File: dumpreq.go

package info (click to toggle)
golang-github-vulcand-oxy 2.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 728 kB
  • sloc: makefile: 14
file content (66 lines) | stat: -rw-r--r-- 1,526 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package utils

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"mime/multipart"
	"net/http"
	"net/url"
)

// SerializableHTTPRequest serializable HTTP request.
//
//nolint:musttag // Cannot be changed more now.
type SerializableHTTPRequest struct {
	Method           string
	URL              *url.URL
	Proto            string // "HTTP/1.0"
	ProtoMajor       int    // 1
	ProtoMinor       int    // 0
	Header           http.Header
	ContentLength    int64
	TransferEncoding []string
	Host             string
	Form             url.Values
	PostForm         url.Values
	MultipartForm    *multipart.Form
	Trailer          http.Header
	RemoteAddr       string
	RequestURI       string
	TLS              *tls.ConnectionState
}

// Clone clone a request.
func Clone(r *http.Request) *SerializableHTTPRequest {
	if r == nil {
		return nil
	}

	rc := new(SerializableHTTPRequest)
	rc.Method = r.Method
	rc.URL = r.URL
	rc.Proto = r.Proto
	rc.ProtoMajor = r.ProtoMajor
	rc.ProtoMinor = r.ProtoMinor
	rc.Header = r.Header
	rc.ContentLength = r.ContentLength
	rc.Host = r.Host
	rc.RemoteAddr = r.RemoteAddr
	rc.RequestURI = r.RequestURI
	return rc
}

// ToJSON serializes to JSON.
func (s *SerializableHTTPRequest) ToJSON() string {
	jsonVal, err := json.Marshal(s)
	if err != nil || jsonVal == nil {
		return fmt.Sprintf("error marshaling SerializableHTTPRequest to json: %s", err)
	}
	return string(jsonVal)
}

// DumpHTTPRequest dump a HTTP request to JSON.
func DumpHTTPRequest(req *http.Request) string {
	return Clone(req).ToJSON()
}