本文整理汇总了Golang中net/http/httputil.DumpRequestOut函数的典型用法代码示例。如果您正苦于以下问题:Golang DumpRequestOut函数的具体用法?Golang DumpRequestOut怎么用?Golang DumpRequestOut使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DumpRequestOut函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Do
// Do sends an API request and returns the API response. The API response is
// JSON decoded and stored in the value pointed to by v, or returned as an
// error if an API error has occurred. If v implements the io.Writer
// interface, the raw response body will be written to v, without attempting to
// first decode it.
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
var err error
if c.DebugHTTP {
// If the request is a multi-part form, then it's probably a
// file upload, in which case we don't want to spewing out the
// file contents into the debug log (especially if it's been
// gzipped)
var requestDump []byte
if strings.Contains(req.Header.Get("Content-Type"), "multipart/form-data") {
requestDump, err = httputil.DumpRequestOut(req, false)
} else {
requestDump, err = httputil.DumpRequestOut(req, true)
}
logger.Debug("ERR: %s\n%s", err, string(requestDump))
}
ts := time.Now()
logger.Debug("%s %s", req.Method, req.URL)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
logger.Debug("↳ %s %s (%s %s)", req.Method, req.URL, resp.Status, time.Now().Sub(ts))
defer resp.Body.Close()
defer io.Copy(ioutil.Discard, resp.Body)
response := newResponse(resp)
if c.DebugHTTP {
responseDump, err := httputil.DumpResponse(resp, true)
logger.Debug("\nERR: %s\n%s", err, string(responseDump))
}
err = checkResponse(resp)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return response, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
}
}
return response, err
}
示例2: createNewFolder
func createNewFolder(authToken string, folder string, folderName string) string {
client := http.Client{}
rObj := Folder{DisplayName: folderName}
payload, err := xml.Marshal(rObj)
if *DEBUG {
fmt.Println("Posting to " + folder + " with:\n" + string(payload))
}
req, err := http.NewRequest("POST", folder, strings.NewReader(string(payload)))
req.Header.Set("Authorization", authToken)
if *DEBUG {
dump, _ := httputil.DumpRequestOut(req, true)
fmt.Println(string(dump))
}
res, err := client.Do(req)
if err != nil {
fmt.Println("ERROR: ")
fmt.Println(err)
}
defer res.Body.Close()
if *DEBUG {
dump, _ := httputil.DumpResponse(res, true)
fmt.Println(string(dump))
}
return res.Header.Get("Location")
}
示例3: get
func (c *BClient) get(url string, data, urlData interface{}) error {
rUrl := getUrl(url, urlData)
req, _ := http.NewRequest("GET", rUrl, nil)
signDataRequest(req, c.accessToken, c.ConsumerKey, c.ConsumerSecret)
if debugOn {
debug(httputil.DumpRequestOut(req, true))
}
resp, err := http.DefaultClient.Do(req)
defer resp.Body.Close()
if debugOn {
debug(httputil.DumpResponse(resp, true))
log.Println("response code:", resp.StatusCode)
}
if resp.StatusCode != 200 {
log.Println("response code:", resp.StatusCode, resp.Status)
return errors.New("Http Status != 200")
}
if err != nil {
return err
}
return json.NewDecoder(resp.Body).Decode(data)
}
示例4: Request
// Request - Trace HTTP Request
func (t Trace) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
// Authorization (S3 v4 signature) Format:
// Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNACEGBGMXBHLEZA/20150524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=bbfaa693c626021bcb5f911cd898a1a30206c1fad6bad1e0eb89e282173bd24c
// Strip out access-key-id from: Credential=<access-key-id>/<date>/<aws-region>/<aws-service>/aws4_request
regCred := regexp.MustCompile("Credential=([A-Z]+)/")
newAuth := regCred.ReplaceAllString(origAuth, "Credential=**REDACTED**/")
// Strip out 256-bit signature from: Signature=<256-bit signature>
regSign := regexp.MustCompile("Signature=([[0-9a-f]+)")
newAuth = regSign.ReplaceAllString(newAuth, "Signature=**REDACTED**")
// Set a temporary redacted auth
req.Header.Set("Authorization", newAuth)
reqTrace, err := httputil.DumpRequestOut(req, false) // Only display header
if err == nil {
console.Debug(string(reqTrace))
}
// Undo
req.Header.Set("Authorization", origAuth)
return err
}
示例5: RoundTrip
// RoundTrip implements the RoundTripper interface.
func (t *TransportLogger) RoundTrip(req *http.Request) (res *http.Response, err error) {
transport := t.Transport
if transport == nil {
transport = http.DefaultTransport
}
writer := t.Writer
if writer == nil {
writer = os.Stdout
}
reqDump, err := httputil.DumpRequestOut(req, true)
writer.Write(reqDump)
writer.Write([]byte("\n"))
res, err = transport.RoundTrip(req)
if err != nil {
return
}
resDump, err := httputil.DumpResponse(res, true)
writer.Write(resDump)
writer.Write([]byte("\n"))
return
}
示例6: DumpRequest
func DumpRequest(req *http.Request, name string) {
dump1, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.WithField("tag", TAG).Errorf("dump of %v request failed", name)
}
ioutil.WriteFile(name, dump1, 0777)
}
示例7: DumpRequest
func DumpRequest(req *http.Request) {
out, err := httputil.DumpRequestOut(req, true)
if err != nil {
panic(err)
}
fmt.Printf("%q\n", out)
}
示例8: RoundTrip
// RoundTrip implements the RoundTripper interface.
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
// Force user agent
req.Header.Set("User-Agent", UserAgent)
// Log request
if t.logHeader || t.logBody {
buf, _ := httputil.DumpRequestOut(req, t.logBody)
Debug(nil, "%s", separatorReq)
Debug(nil, "%s", "HTTP REQUEST")
Debug(nil, "%s", string(buf))
Debug(nil, "%s", separatorReq)
}
// Do round trip
resp, err = t.Transport.RoundTrip(req)
// Log response
if t.logHeader || t.logBody {
Debug(nil, "%s", separatorResp)
Debug(nil, "%s", "HTTP RESPONSE")
if err != nil {
Debug(nil, "Error: %v", err)
} else {
buf, _ := httputil.DumpResponse(resp, t.logBody)
Debug(nil, "%s", string(buf))
}
Debug(nil, "%s", separatorResp)
}
if err == nil {
checkServerTime(req, resp)
}
return resp, err
}
示例9: Run
func (ts *TestSuite) Run(server *httptest.Server) {
for _, test := range ts.Tests {
session := &TestSession{
Server: server,
Test: &test,
Request: &http.Request{},
}
work := func() {
for _, cr := range test.Criteria {
cr.Setup(session)
}
cl := http.Client{}
res, err := cl.Do(session.Request)
Check(err)
session.Response = res
for _, cr := range test.Criteria {
cr.Check(session)
}
}
err := Catch(work)
if err != nil {
rawReq, terr := httputil.DumpRequestOut(session.Request, true)
Check(terr)
rawRes, terr := httputil.DumpResponse(session.Response, true)
Check(terr)
ts.T.Errorf("Error running test: %#v\n\nTEST DESCRIPTION:\n\n%s\nREQUEST:\n\n%s\nRESPONSE:\n\n%s\n", err, test.Describe(), string(rawReq), string(rawRes))
}
}
}
示例10: main
func main() {
var body []byte
var response *http.Response
var request *http.Request
url := "http://api.open-notify.org/iss-now.json"
request, err := http.NewRequest("GET", url, nil)
if err == nil {
request.Header.Add("Content-Type", "application/json")
debug(httputil.DumpRequestOut(request, true))
response, err = (&http.Client{}).Do(request)
}
if err == nil {
defer response.Body.Close()
debug(httputil.DumpResponse(response, true))
body, err = ioutil.ReadAll(response.Body)
}
if err == nil {
fmt.Printf("%s\n\n", body)
} else {
log.Fatalf("Error: %s\n\n", err)
}
var data IssNow
err = json.Unmarshal(body, &data)
if err != nil {
panic(err)
}
// fmt.Printf("%v\n", data)
fmt.Printf("Time: %v | Lat./Long. : %v, %v\n", data.Timestamp, data.Position.Latitude, data.Position.Longitude)
}
示例11: do
// Main method, opens the connection, sets basic auth, applies headers,
// parses response json.
func (r *Resource) do(method string) (*Resource, error) {
url := *r.Api.BaseUrl
if len(url.Path) > 0 {
url.Path += "/" + r.Url
} else {
url.Path = r.Url
}
if r.Api.PathSuffix != "" {
url.Path += r.Api.PathSuffix
}
url.RawQuery = r.QueryValues.Encode()
req, err := http.NewRequest(method, url.String(), r.Payload)
if err != nil {
return r, err
}
if r.Api.BasicAuth != nil {
req.SetBasicAuth(r.Api.BasicAuth.Username, r.Api.BasicAuth.Password)
}
if r.Headers != nil {
for k, _ := range r.Headers {
req.Header.Set(k, r.Headers.Get(k))
}
}
b, _ := httputil.DumpRequestOut(req, true)
log.Printf("--- DUMP REQUEST:\n%s\n\n", string(b))
resp, err := r.Api.Client.Do(req)
if err != nil {
return r, err
}
// Read the content
var bodyBytes []byte
if resp.Body != nil {
bodyBytes, _ = ioutil.ReadAll(resp.Body)
resp.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
b, _ = httputil.DumpResponse(resp, true)
log.Printf("=== DUMP RESPONSE:\n%s\n\n", string(b))
resp.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
}
r.Raw = resp
if resp.StatusCode >= 400 {
return r, nil
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(r.Response)
if err != nil {
return r, err
}
return r, nil
}
示例12: logRequest
func (tr debugTransport) logRequest(req *http.Request) {
dump, err := httputil.DumpRequestOut(req, true)
if err != nil {
fmt.Fprintf(tr.Writer, "%s: %s\n", "could not dump request", err)
}
fmt.Fprint(tr.Writer, string(dump))
}
示例13: testFallbackServer
// Perform the test of an individual server
func testFallbackServer(fb *client.ChainedServerInfo, workerID int) (output fullOutput) {
// Test connectivity
fb.Pipelined = true
dialer, err := fb.Dialer(DeviceID)
if err != nil {
output.err = fmt.Errorf("%v: error building dialer: %v", fb.Addr, err)
return
}
c := &http.Client{
Transport: &http.Transport{
Dial: dialer.Dial,
},
}
req, err := http.NewRequest("GET", "http://www.google.com/humans.txt", nil)
if err != nil {
output.err = fmt.Errorf("%v: NewRequest to humans.txt failed: %v", fb.Addr, err)
return
}
if *verbose {
reqStr, _ := httputil.DumpRequestOut(req, true)
output.info = []string{"\n" + string(reqStr)}
}
req.Header.Set("X-LANTERN-AUTH-TOKEN", fb.AuthToken)
resp, err := c.Do(req)
if err != nil {
output.err = fmt.Errorf("%v: requesting humans.txt failed: %v", fb.Addr, err)
return
}
if *verbose {
respStr, _ := httputil.DumpResponse(resp, true)
output.info = append(output.info, "\n"+string(respStr))
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Debugf("Unable to close response body: %v", err)
}
}()
if resp.StatusCode != 200 {
output.err = fmt.Errorf("%v: bad status code: %v", fb.Addr, resp.StatusCode)
return
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
output.err = fmt.Errorf("%v: error reading response body: %v", fb.Addr, err)
return
}
body := string(bytes)
if body != expectedBody {
output.err = fmt.Errorf("%v: wrong body: %s", fb.Addr, body)
return
}
log.Debugf("Worker %d: Fallback %v OK.\n", workerID, fb.Addr)
if *verify {
verifyFallback(fb, c)
}
return
}
示例14: uploadFile
func uploadFile(authToken string, fileLocation string, file string) {
client := http.Client{}
fData, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err.Error())
}
req, err := http.NewRequest("PUT", fileLocation+"/data", strings.NewReader(string(fData)))
req.Header.Set("Authorization", authToken)
req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set("Content-Length", fmt.Sprint(len(fData)))
if *DEBUG {
dump, _ := httputil.DumpRequestOut(req, true)
fmt.Println(string(dump))
}
res, err := client.Do(req)
if err != nil {
fmt.Println("ERROR: ")
fmt.Println(err)
}
defer res.Body.Close()
if *DEBUG {
dump, _ := httputil.DumpResponse(res, true)
fmt.Println(string(dump))
}
}
示例15: getNewFileLocation
func getNewFileLocation(authToken string, folder string, fileName string) string {
client := http.Client{}
payload := "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<file>\n" +
"<displayName>" + fileName + "</displayName>\n" +
"<mediaType>" + getFileTypeForFile(fileName) + "</mediaType>\n" +
"</file>\n"
if *DEBUG {
fmt.Println("Posting to " + REFRESH_URL + " with:\n" + payload)
}
req, err := http.NewRequest("POST", folder, strings.NewReader(string(payload)))
req.Header.Set("Authorization", authToken)
if *DEBUG {
dump, _ := httputil.DumpRequestOut(req, true)
fmt.Println(string(dump))
}
res, err := client.Do(req)
if err != nil {
fmt.Println("ERROR: ")
fmt.Println(err)
}
defer res.Body.Close()
if *DEBUG {
dump, _ := httputil.DumpResponse(res, true)
fmt.Println(string(dump))
}
return res.Header.Get("Location")
}