本文整理匯總了Golang中http.NewRequest函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewRequest函數的具體用法?Golang NewRequest怎麽用?Golang NewRequest使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewRequest函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: send
func (this *Neo4j) send(url string, data string) (string, os.Error) {
var (
resp *http.Response // http response
buf bytes.Buffer // contains http response body
err os.Error
)
if len(url) < 1 {
url = this.URL + "node" // default path
}
client := new(http.Client)
switch strings.ToLower(this.Method) { // which http method
case "delete":
req, e := http.NewRequest("DELETE", url, nil)
if e != nil {
err = e
break
}
resp, err = client.Do(req)
case "post":
body := strings.NewReader(data)
resp, err = client.Post(url,
"application/json",
body,
)
case "put":
body := strings.NewReader(data)
req, e := http.NewRequest("PUT", url, body)
if e != nil {
err = e
break
}
req.Header.Set("Content-Type", "application/json")
resp, err = client.Do(req)
case "get":
fallthrough
default:
resp, err = client.Get(url)
}
if err != nil {
return "", err
}
defer func() {
if resp.Body != nil {
resp.Body.Close()
}
}()
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return "", err
}
this.StatusCode = resp.StatusCode // the calling method should do more inspection with chkStatusCode() method and determine if the operation was successful or not.
return buf.String(), nil
}
示例2: TestRedirectSlash
func TestRedirectSlash(t *testing.T) {
var route *Route
r := new(Router)
r.RedirectSlash(false)
route = r.NewRoute()
if route.redirectSlash != false {
t.Errorf("Expected false redirectSlash.")
}
r.RedirectSlash(true)
route = r.NewRoute()
if route.redirectSlash != true {
t.Errorf("Expected true redirectSlash.")
}
route = newRoute().RedirectSlash(true).Path("/{arg1}/{arg2:[0-9]+}/")
request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil)
match, _ := route.Match(request)
vars := Vars(request)
if vars["arg1"] != "foo" {
t.Errorf("Expected foo.")
}
if vars["arg2"] != "123" {
t.Errorf("Expected 123.")
}
rsp := NewRecorder()
match.Handler.ServeHTTP(rsp, request)
if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" {
t.Errorf("Expected redirect header.")
}
route = newRoute().RedirectSlash(true).Path("/{arg1}/{arg2:[0-9]+}")
request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil)
match, _ = route.Match(request)
vars = Vars(request)
if vars["arg1"] != "foo" {
t.Errorf("Expected foo.")
}
if vars["arg2"] != "123" {
t.Errorf("Expected 123.")
}
rsp = NewRecorder()
match.Handler.ServeHTTP(rsp, request)
if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" {
t.Errorf("Expected redirect header.")
}
}
示例3: TestRoutingFailure
func TestRoutingFailure(t *testing.T) {
// Compile the stack
routingStack := new(Stack)
routes := make(map[string]App)
routes["/a"] = routingATestServer
routes["/b"] = routingBTestServer
routingStack.Middleware(Routing(routes))
routingApp := routingStack.Compile(routingTestServer)
// Request against it
request, err := http.NewRequest("GET", "http://localhost:3000/c", nil)
status, _, body := routingApp(Env{"mango.request": &Request{request}})
if err != nil {
t.Error(err)
}
if status != 200 {
t.Error("Expected status to equal 200, got:", status)
}
expected := "Hello World!"
if string(body) != expected {
t.Error("Expected body:", string(body), "to equal:", expected)
}
}
示例4: TestPathMatcher
func TestPathMatcher(t *testing.T) {
for _, v := range pathMatcherTests {
request, _ := http.NewRequest("GET", v.url, nil)
_, result := v.matcher.Match(request)
vars := Vars(request)
if result != v.result {
if v.result {
t.Errorf("%#v: should match %v.", v.matcher, v.url)
} else {
t.Errorf("%#v: should not match %v.", v.matcher, v.url)
}
}
if result {
if len(vars) != len(v.vars) {
t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars))
}
for name, value := range vars {
if v.vars[name] != value {
t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value)
}
}
} else {
if len(vars) != 0 {
t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars))
}
}
}
}
示例5: Act
// POST /jobs/id/stop or POST /jobs/id/kill
func (this RestJsonMongo) Act(rw http.ResponseWriter, parts []string, r *http.Request) (item interface{}) {
logger.Debug("Act(%v):%v", r.URL.Path, parts)
if len(parts) < 2 {
if err := this.LoadJson(r, item); err != nil {
http.Error(rw, err.String(), http.StatusBadRequest)
return
} else {
id := parts[1]
if err := this.Store.Update(id, item); err != nil {
http.Error(rw, err.String(), http.StatusBadRequest)
return
}
}
}
if this.Target == nil {
http.Error(rw, fmt.Sprintf("service not found %v", r.URL.Path), http.StatusNotImplemented)
return
}
preq, _ := http.NewRequest(r.Method, r.URL.Path, r.Body)
proxy := http.NewSingleHostReverseProxy(this.Target)
go proxy.ServeHTTP(rw, preq)
return
}
示例6: TestRedirect
func TestRedirect(t *testing.T) {
// Compile the stack
redirectApp := new(Stack).Compile(redirectTestServer)
// Request against it
request, err := http.NewRequest("GET", "http://localhost:3000/", nil)
status, headers, body := redirectApp(Env{"mango.request": &Request{request}})
if err != nil {
t.Error(err)
}
if status != 302 {
t.Error("Expected status to equal 302, got:", status)
}
expected := "/somewhere"
if headers["Location"][0] != expected {
t.Error("Expected Location header to be: \"", expected, "\" got: \"", headers["Location"][0], "\"")
}
expectedBody := Body("")
if body != expectedBody {
t.Error("Expected body to be: \"", expected, "\" got: \"", body, "\"")
}
}
示例7: TestJSONPNoCallback
func TestJSONPNoCallback(t *testing.T) {
// Compile the stack
jsonpStack := new(Stack)
jsonpStack.Middleware(JSONP)
jsonpApp := jsonpStack.Compile(jsonServer)
// Request against it
request, err := http.NewRequest("GET", "http://localhost:3000/", nil)
status, headers, body := jsonpApp(Env{"mango.request": &Request{request}})
if err != nil {
t.Error(err)
}
if status != 200 {
t.Error("Expected status to equal 200, got:", status)
}
if headers.Get("Content-Type") != "application/json" {
t.Error("Expected Content-Type to equal \"application/json\", got:", headers.Get("Content-Type"))
}
if headers.Get("Content-Length") != "13" {
t.Error("Expected Content-Length to equal \"13\", got:", headers.Get("Content-Length"))
}
expected := "{\"foo\":\"bar\"}"
if string(body) != expected {
t.Error("Expected body:", string(body), "to equal:", expected)
}
}
示例8: C1Logout
func C1Logout(c appengine.Context) os.Error {
u := user.Current(c).Email
itm, err := memcache.Get(c, u+"__c1Sess")
if err != nil && err != memcache.ErrCacheMiss {
return err
}
if err == memcache.ErrCacheMiss {
return nil
}
skey := string(itm.Value)
session := c1SessionCookie(skey)
r, err := http.NewRequest("GET", "https://www.cadetone.aafc.org.au/logout.php", nil)
if err != nil {
return err
}
injectSession(r, session)
client := GetClient(c)
_, err = client.Do(r)
if err != nil {
return err
}
memcache.Delete(c, u+"__c1Sess")
return nil
}
示例9: ping
func (u *Upstream) ping() (up bool, ok bool) {
if u.PingPath != "" {
// the url must be syntactically valid for this to work but the host will be ignored because we
// are overriding the connection always
request, err := http.NewRequest("GET", "http://localhost"+u.PingPath, nil)
request.Header.Set("Connection", "Keep-Alive") // not sure if this should be here for a ping
if err != nil {
falcore.Error("Bad Ping request: %v", err)
return false, true
}
res, err := u.transport.RoundTrip(request)
if err != nil {
falcore.Error("Failed Ping to %v:%v: %v", u.Host, u.Port, err)
return false, true
} else {
res.Body.Close()
}
if res.StatusCode == 200 {
return true, true
}
falcore.Error("Failed Ping to %v:%v: %v", u.Host, u.Port, res.Status)
// bad status
return false, true
}
return false, false
}
示例10: Do
func (c *CurrentLocationDeleteCall) Do() os.Error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative("https://www.googleapis.com/latitude/v1/", "currentLocation")
urls += "?" + params.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes the authenticated user's current location.",
// "httpMethod": "DELETE",
// "id": "latitude.currentLocation.delete",
// "path": "currentLocation",
// "scopes": [
// "https://www.googleapis.com/auth/latitude.all.best",
// "https://www.googleapis.com/auth/latitude.all.city",
// "https://www.googleapis.com/auth/latitude.current.best",
// "https://www.googleapis.com/auth/latitude.current.city"
// ]
// }
}
示例11: TestUpdateUserAccountMissingSignature
func TestUpdateUserAccountMissingSignature(t *testing.T) {
ds, wm := initializeUpdateUserAccountDS()
gw, _ := ds.FindUserAccountByUsername("firstpresident")
otherUser, _ := ds.FindUserAccountByUsername("secondpresident")
anobj, _ := jsonhelper.Marshal(otherUser)
jsonobj := anobj.(jsonhelper.JSONObject)
jsonobj.Set("name", "GW")
jsonobj.Set("email", "[email protected]")
jsonobj.Set("address", "Pre-White House")
otherUser = new(dm.User)
otherUser.InitFromJSONObject(jsonobj)
jsonbuf, _ := json.Marshal(jsonobj)
req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/account/user/update/" + gw.Id, bytes.NewBuffer(jsonbuf))
req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
req.Header.Set("Accept-Charset", "utf-8")
req.Header.Set("Accept-Encoding", "identity")
req.Header.Set("Accept-Language", "en-us")
req.Header.Set("Connection", "close")
resp := webmachine.NewMockResponseWriter(req)
wm.ServeHTTP(resp, req)
if resp.StatusCode != http.StatusUnauthorized {
t.Error("Expected ", http.StatusUnauthorized, " status code but received ", resp.StatusCode)
}
}
示例12: TestUpdateUserAccountInvalidUserId
func TestUpdateUserAccountInvalidUserId(t *testing.T) {
ds, wm := initializeUpdateUserAccountDS()
gw, _ := ds.FindUserAccountByUsername("firstpresident")
accessKeys, _, _ := ds.RetrieveUserKeys(gw.Id, nil, 1)
accessKey := accessKeys[0]
otherUser, _ := ds.FindUserAccountByUsername("secondpresident")
anobj, _ := jsonhelper.Marshal(otherUser)
jsonobj := anobj.(jsonhelper.JSONObject)
jsonobj.Set("name", "Tom J")
jsonobj.Set("email", "[email protected]")
jsonobj.Set("address", "White House")
otherUser = new(dm.User)
otherUser.InitFromJSONObject(jsonobj)
jsonbuf, _ := json.Marshal(jsonobj)
req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/account/user/update/sdflsjflsjfslf", bytes.NewBuffer(jsonbuf))
req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
req.Header.Set("Accept-Charset", "utf-8")
req.Header.Set("Accept-Encoding", "identity")
req.Header.Set("Accept-Language", "en-us")
req.Header.Set("Connection", "close")
apiutil.NewSigner(accessKey.Id, accessKey.PrivateKey).SignRequest(req, 0)
resp := webmachine.NewMockResponseWriter(req)
wm.ServeHTTP(resp, req)
if resp.StatusCode != http.StatusNotFound {
t.Error("Expected ", http.StatusNotFound, " status code but received ", resp.StatusCode)
}
}
示例13: Do
func (c *WebResourceGetTokenCall) Do() (*SiteverificationWebResourceGettokenResponse, os.Error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["verificationMethod"]; ok {
params.Set("verificationMethod", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["identifier"]; ok {
params.Set("identifier", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["type"]; ok {
params.Set("type", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative("https://www.googleapis.com/siteVerification/v1/", "token")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(SiteverificationWebResourceGettokenResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Get a verification token for placing on a website or domain.",
// "httpMethod": "GET",
// "id": "siteVerification.webResource.getToken",
// "parameters": {
// "identifier": {
// "description": "The URL or domain to verify.",
// "location": "query",
// "type": "string"
// },
// "type": {
// "description": "Type of resource to verify. Can be 'site' (URL) or 'inet_domain' (domain name).",
// "location": "query",
// "type": "string"
// },
// "verificationMethod": {
// "description": "The method to use for verifying a site or domain.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "token",
// "response": {
// "$ref": "SiteverificationWebResourceGettokenResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/siteverification"
// ]
// }
}
示例14: slurpURL
func slurpURL(urlStr string) []byte {
diskFile := filepath.Join(os.TempDir(), "google-api-cache-"+url.QueryEscape(urlStr))
if *useCache {
bs, err := ioutil.ReadFile(diskFile)
if err == nil && len(bs) > 0 {
return bs
}
}
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
log.Fatal(err)
}
if *publicOnly {
req.Header.Add("X-User-IP", "0.0.0.0") // hack
}
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("Error fetching URL %s: %v", urlStr, err)
}
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalf("Error reading body of URL %s: %v", urlStr, err)
}
if *useCache {
if err := ioutil.WriteFile(diskFile, bs, 0666); err != nil {
log.Printf("Warning: failed to write JSON of %s to disk file %s: %v", urlStr, diskFile, err)
}
}
return bs
}
示例15: handle_http
func handle_http(responseWrite http.ResponseWriter, request *http.Request) {
var proxyResponse *http.Response
var proxyResponseError os.Error
proxyHost := strings.Split(request.URL.Path[6:], "/")[0]
fmt.Printf("%s %s %s\n", request.Method, request.RawURL, request.RemoteAddr)
//TODO https
url := "http://" + request.URL.Path[6:]
proxyRequest, _ := http.NewRequest(request.Method, url, nil)
proxy := &http.Client{}
proxyResponse, proxyResponseError = proxy.Do(proxyRequest)
if proxyResponseError != nil {
http.NotFound(responseWrite, request)
return
}
for header := range proxyResponse.Header {
responseWrite.Header().Add(header, proxyResponse.Header.Get(header))
}
contentType := strings.Split(proxyResponse.Header.Get("Content-Type"), ";")[0]
if proxyResponseError != nil {
fmt.Fprintf(responseWrite, "pizda\n")
} else if ReplacemendContentType[contentType] {
body, _ := ioutil.ReadAll(proxyResponse.Body)
defer proxyResponse.Body.Close()
bodyString := replace_url(string(body), "/http/", proxyHost)
responseWrite.Write([]byte(bodyString))
} else {
io.Copy(responseWrite, proxyResponse.Body)
}
}