github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/net/http/repo/2_send_cmd.go (about) 1 package repo 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "html" 8 "net/http" 9 10 "github.com/pbberlin/tools/appengine/instance_mgt" 11 "github.com/pbberlin/tools/net/http/fetch" 12 "github.com/pbberlin/tools/net/http/loghttp" 13 "github.com/pbberlin/tools/net/http/tplx" 14 ) 15 16 // Submit test commands internally, without http request. 17 func staticFetchDirect(w http.ResponseWriter, r *http.Request, m map[string]interface{}) { 18 FetchHTML(w, r, testCommands) 19 } 20 21 // Submit test commands by http posting them. 22 func staticFetchViaPosting2Receiver(w http.ResponseWriter, r *http.Request, m map[string]interface{}) { 23 24 lg, lge := loghttp.Logger(w, r) 25 26 wpf(w, tplx.ExecTplHelper(tplx.Head, map[string]interface{}{"HtmlTitle": "JSON Post"})) 27 defer wpf(w, tplx.Foot) 28 29 wpf(w, "<pre>") 30 defer wpf(w, "</pre>") 31 32 b, err := Post2Receiver(r, testCommands) 33 34 lge(err) 35 lg("msg from Post2Receiver:") 36 lg(b.String()) 37 38 } 39 40 // Post2Receiver takes commands and http posts them to 41 // the command receiver 42 func Post2Receiver(r *http.Request, commands []FetchCommand) (*bytes.Buffer, error) { 43 44 b := new(bytes.Buffer) 45 46 if commands == nil || len(commands) == 0 { 47 return b, fmt.Errorf("Slice of commands nil or empty %v", commands) 48 } 49 50 ii := instance_mgt.Get(r) 51 fullURL := fmt.Sprintf("https://%s%s", ii.PureHostname, uriFetchCommandReceiver) 52 wpf(b, "sending to URL: %v\n", fullURL) 53 54 bcommands, err := json.MarshalIndent(commands, "", "\t") 55 if err != nil { 56 wpf(b, "marshalling to []byte failed\n") 57 return b, err 58 } 59 60 req, err := http.NewRequest("POST", fullURL, bytes.NewBuffer(bcommands)) 61 if err != nil { 62 wpf(b, "creation of POST request failed\n") 63 return b, err 64 } 65 req.Header.Set("X-Custom-Header-Counter", "nocounter") 66 req.Header.Set("Content-Type", "application/json") 67 68 bts, reqUrl, err := fetch.UrlGetter(r, fetch.Options{Req: req}) 69 _, _ = bts, reqUrl 70 if err != nil { 71 wpf(b, "Sending the POST request failed\n") 72 return b, err 73 } 74 75 wpf(b, "effective req url: %v\n", reqUrl) 76 wpf(b, "response body:\n") 77 wpf(b, "%s\n", html.EscapeString(string(bts))) 78 79 return b, nil 80 }