コード例 #1
0
ファイル: neo4j.go プロジェクト: searchify/Neo4j-GO
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
0
ファイル: mux_test.go プロジェクト: klinster/Bessie
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
0
ファイル: routing_test.go プロジェクト: qrush/higo
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
0
ファイル: mux_test.go プロジェクト: klinster/Bessie
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
0
// 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
0
ファイル: redirect_test.go プロジェクト: victorcoder/mango
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
0
ファイル: jsonp_test.go プロジェクト: qrush/higo
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
0
ファイル: fetch.go プロジェクト: qtse/go_fetch
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
0
ファイル: upstream.go プロジェクト: repos-go/falcore
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
0
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
0
ファイル: update_test.go プロジェクト: pombredanne/dsocial.go
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", "*****@*****.**")
    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
0
ファイル: update_test.go プロジェクト: pombredanne/dsocial.go
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", "*****@*****.**")
    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
0
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
0
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
0
ファイル: anonymizer.go プロジェクト: kalloc/goanonymizer
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)
	}
}
コード例 #16
0
ファイル: campfire.go プロジェクト: wjlroe/gocampfire
func PostEmpty(url_ string) (response *http.Response, err os.Error) {
	parsed_url := ParseURL(url_)
	fmt.Printf("Going to post to: %s\n", url_)
	request, err := http.NewRequest("POST", parsed_url.String(), nil)
	response, err = http.DefaultClient.Do(request)
	return response, err
}
コード例 #17
0
ファイル: static_test.go プロジェクト: victorcoder/mango
func TestStaticBinaryFile(t *testing.T) {
	// Compile the stack
	staticStack := new(Stack)
	staticStack.Middleware(Static("./static"))
	staticApp := staticStack.Compile(staticTestServer)

	// Request against it
	request, err := http.NewRequest("GET", "http://localhost:3000/binary_file.png", nil)
	status, _, body := staticApp(Env{"mango.request": &Request{request}})

	if err != nil {
		t.Error(err)
	}

	if status != 200 {
		t.Error("Expected status to equal 200, got:", status)
	}

	expected, err := ioutil.ReadFile("./static/binary_file.png")
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare([]byte(body), []byte(expected)) != 0 {
		t.Error("Expected body to equal ./static/binary_file.png")
	}
}
コード例 #18
0
ファイル: main.go プロジェクト: andradeandrey/goissue
// showComments print comment list.
func showComments(auth string, id string) {
	req, err := http.NewRequest("GET", "https://code.google.com/feeds/issues/p/"+project+"/issues/"+id+"/comments/full", nil)
	if err != nil {
		log.Fatal("failed to get comments:", err)
	}
	req.Header.Set("Authorization", "GoogleLogin "+auth)
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal("failed to get comments:", err)
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		log.Fatal("failed to authenticate:", res.Status)
	}
	var feed Feed
	err = xml.Unmarshal(res.Body, &feed)
	if err != nil {
		log.Fatal("failed to get comments:", err)
	}
	for _, entry := range feed.Entry {
		doc, err := html.Parse(strings.NewReader(entry.Content))
		if err != nil {
			log.Fatal("failed to parse xml:", err)
		}
		text, err := dump(doc)
		if err != nil {
			log.Fatal("failed to parse xml:", err)
		}
		println(entry.Title, "\n", text)
	}
}
コード例 #19
0
ファイル: static_test.go プロジェクト: victorcoder/mango
func TestStaticSuccess(t *testing.T) {
	// Compile the stack
	staticStack := new(Stack)
	staticStack.Middleware(Static("./static"))
	staticApp := staticStack.Compile(staticTestServer)

	// Request against it
	request, err := http.NewRequest("GET", "http://localhost:3000/static.html", nil)
	status, headers, body := staticApp(Env{"mango.request": &Request{request}})

	if err != nil {
		t.Error(err)
	}

	if status != 200 {
		t.Error("Expected status to equal 200, got:", status)
	}

	expected := "<h1>I'm a static test file</h1>\n"
	if string(body) != expected {
		t.Error("Expected body:", string(body), "to equal:", expected)
	}

	expected = "text/html"
	got := headers.Get("Content-Type")
	if got != expected {
		t.Error("Expected Content-Type:", got, "to equal:", expected)
	}
}
コード例 #20
0
ファイル: jsonp_test.go プロジェクト: qrush/higo
func TestNonJSONPSuccess(t *testing.T) {
	// Compile the stack
	nonJsonpStack := new(Stack)
	nonJsonpStack.Middleware(JSONP)
	nonJsonpApp := nonJsonpStack.Compile(nonJsonServer)

	// Request against it
	request, err := http.NewRequest("GET", "http://localhost:3000/?callback=parseResponse", nil)
	status, headers, body := nonJsonpApp(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") != "text/html" {
		t.Error("Expected Content-Type to equal \"text/html\", got:", headers.Get("Content-Type"))
	}

	if headers.Get("Content-Length") != "" {
		t.Error("Expected Content-Length to equal \"\", got:", headers.Get("Content-Length"))
	}

	expected := "<h1>Hello World!</h1>"
	if string(body) != expected {
		t.Error("Expected body:", string(body), "to equal:", expected)
	}
}
コード例 #21
0
ファイル: cmd-google.go プロジェクト: raylu/rbot
// make a GET request with a fake user agent
// this is definitely not for those undocumented Google APIs
func getUserAgent(urlstr string) ([]byte, os.Error) {
	urlobj, err := url.Parse(urlstr)
	if err != nil {
		return nil, err
	}

	conn, err := net.Dial("tcp", urlobj.Host+":http")
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("GET", urlstr, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", "Mozilla/5.0")

	httpconn := http.NewClientConn(conn, nil)
	response, err := httpconn.Do(req)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	b, err := ioutil.ReadAll(response.Body)
	return b, err
}
コード例 #22
0
func (c *WebResourceListCall) Do() (*SiteverificationWebResourceListResponse, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/siteVerification/v1/", "webResource")
	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(SiteverificationWebResourceListResponse)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Get the list of your verified websites and domains.",
	//   "httpMethod": "GET",
	//   "id": "siteVerification.webResource.list",
	//   "path": "webResource",
	//   "response": {
	//     "$ref": "SiteverificationWebResourceListResponse"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/siteverification"
	//   ]
	// }

}
コード例 #23
0
ファイル: jsonp_test.go プロジェクト: qrush/higo
func TestJSONPInvalidCallback(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/?callback=invalid(callback)", nil)
	status, headers, body := jsonpApp(Env{"mango.request": &Request{request}})

	if err != nil {
		t.Error(err)
	}

	if status != 400 {
		t.Error("Expected status to equal 400, got:", status)
	}

	if headers.Get("Content-Type") != "text/plain" {
		t.Error("Expected Content-Type to equal \"text/plain\", got:", headers.Get("Content-Type"))
	}

	if headers.Get("Content-Length") != "11" {
		t.Error("Expected Content-Length to equal \"11\", got:", headers.Get("Content-Length"))
	}

	expected := "Bad Request"
	if string(body) != expected {
		t.Error("Expected body:", string(body), "to equal:", expected)
	}
}
コード例 #24
0
ファイル: client.go プロジェクト: rvijax/camlistore
func newReq(url string) *http.Request {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		panic(fmt.Sprintf("s3 client; invalid URL: %v", err))
	}
	req.Header.Set("User-Agent", "go-camlistore-s3")
	return req
}
コード例 #25
0
ファイル: cstore_test.go プロジェクト: emk/cstore
// Send an HTTP PUT request.  The caller is responsible for calling
// resp.Body.Close().
func put(client *http.Client, url, data string) (resp *http.Response, err os.Error) {
	req, err := http.NewRequest("PUT", url, strings.NewReader(data))
	if err != nil {
		return
	}
	resp, err = client.Do(req)
	return
}
コード例 #26
0
ファイル: client.go プロジェクト: ipeet/camlistore
func (c *Client) newRequest(method, url string) *http.Request {
	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		panic(err.String())
	}
	c.addAuthHeader(req)
	return req
}
コード例 #27
0
ファイル: ocp.go プロジェクト: conatus/ocp2
func Get(url string) (*http.Response, os.Error) {
	req, err := http.NewRequest("GET", url, nil)
	req.Header.Add("User-Agent", useragent)
	if err != nil {
		return nil, err
	}
	return client.Do(req)
}
コード例 #28
0
ファイル: images.go プロジェクト: cmc333333/fragspace
func (proxy *Proxy) ListImages() *ImagesGet {
	req, err := http.NewRequest("GET", proxy.auth.Url+"/images/detail", nil)
	if err != nil {
		panic(lib.ServerError{"could not create request: " + err.String()})
	}
	images := new(ImagesGet)
	proxy.execute(req, images)
	return images
}
コード例 #29
0
func (c *TasksDeleteCall) Do() os.Error {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/taskqueue/v1beta1/projects/", "{project}/taskqueues/{taskqueue}/tasks/{task}")
	urls = strings.Replace(urls, "{project}", cleanPathString(c.project), 1)
	urls = strings.Replace(urls, "{taskqueue}", cleanPathString(c.taskqueue), 1)
	urls = strings.Replace(urls, "{task}", cleanPathString(c.task), 1)
	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": "Delete a task from a TaskQueue.",
	//   "httpMethod": "DELETE",
	//   "id": "taskqueue.tasks.delete",
	//   "parameterOrder": [
	//     "project",
	//     "taskqueue",
	//     "task"
	//   ],
	//   "parameters": {
	//     "project": {
	//       "description": "The project under which the queue lies.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     },
	//     "task": {
	//       "description": "The id of the task to delete.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     },
	//     "taskqueue": {
	//       "description": "The taskqueue to delete a task from.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     }
	//   },
	//   "path": "{project}/taskqueues/{taskqueue}/tasks/{task}",
	//   "scopes": [
	//     "https://www.googleapis.com/auth/taskqueue",
	//     "https://www.googleapis.com/auth/taskqueue.consumer"
	//   ]
	// }

}
コード例 #30
0
func (c *BadgesGetCall) Do() (*Badge, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/orkut/v2/", "people/{userId}/badges/{badgeId}")
	urls = strings.Replace(urls, "{userId}", cleanPathString(c.userId), 1)
	urls = strings.Replace(urls, "{badgeId}", strconv.Itoa64(c.badgeId), 1)
	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(Badge)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Retrieves a badge from a user.",
	//   "httpMethod": "GET",
	//   "id": "orkut.badges.get",
	//   "parameterOrder": [
	//     "userId",
	//     "badgeId"
	//   ],
	//   "parameters": {
	//     "badgeId": {
	//       "description": "The ID of the badge that will be retrieved.",
	//       "format": "int64",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     },
	//     "userId": {
	//       "description": "The ID of the user whose badges will be listed. Can be me to refer to caller.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     }
	//   },
	//   "path": "people/{userId}/badges/{badgeId}",
	//   "response": {
	//     "$ref": "Badge"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/orkut",
	//     "https://www.googleapis.com/auth/orkut.readonly"
	//   ]
	// }

}