示例#1
0
func (self *Federation) downloadBlob(rawurl, blobref string) (dependencies []string, err os.Error) {
	// Get the blob
	var client http.Client
	req, err := client.Get(rawurl + "?blobref=" + http.URLEscape(blobref))
	if err != nil {
		return nil, err
	}
	// TODO: Improve for large files
	blob, err := ioutil.ReadAll(req.Body)
	if err != nil {
		log.Printf("Error reading request body")
		return nil, err
	}
	log.Printf("Downloaded %v\n", string(blob))
	req.Body.Close()
	self.store.StoreBlob(blob, "")
	// Check whether the retrieved blob is a schema blob
	mimetype := grapher.MimeType(blob)
	if mimetype == "application/x-lightwave-schema" {
		var schema depSchema
		err = json.Unmarshal(blob, &schema)
		if err != nil {
			log.Printf("Malformed schema blob: %v\n", err)
			return nil, err
		}
		dependencies = schema.Dependencies
	}
	return
}
示例#2
0
// postPhoto uses the Buzz API to post the image to the user's Buzz stream.
func postPhoto(client *http.Client, photoURL string) error {
	const url = "https://www.googleapis.com/buzz/v1/activities/@me/@self"
	const text = "Moustachio"

	type m map[string]interface{}
	post := m{"data": m{"object": m{
		"type":    "note",
		"content": text,
		"attachments": []m{{
			"type":    "photo",
			"content": text,
			"links": m{
				"enclosure": []m{{
					"href": photoURL,
					"type": "image/jpeg",
				}},
			},
		}},
	}}}

	b, err := json.Marshal(post)
	if err != nil {
		return err
	}
	resp, err := client.Post(url, "application/json", bytes.NewBuffer(b))
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return errors.New("invalid post " + resp.Status)
	}
	return nil
}
示例#3
0
文件: verify.go 项目: tobi/go-openid
// Like Verify on a parsed URL
func VerifyValues(values url.Values) (grant bool, identifier string, err error) {
	err = nil

	var postArgs url.Values
	postArgs = url.Values(map[string][]string{})

	// Create the url
	URLEndPoint := values.Get("openid.op_endpoint")
	if URLEndPoint == "" {
		log.Printf("no openid.op_endpoint")
		return false, "", errors.New("no openid.op_endpoint")
	}
	for k, v := range values {
		postArgs[k] = v
	}
	postArgs.Set("openid.mode", "check_authentication")
	postContent := postArgs.Encode()

	// Post the request
	var client = new(http.Client)
	postReader := bytes.NewBuffer([]byte(postContent))
	response, err := client.Post(URLEndPoint, "application/x-www-form-urlencoded", postReader)
	if err != nil {
		log.Printf("VerifyValues failed at post")
		return false, "", err
	}

	// Parse the response
	// Convert the reader
	// We limit the size of the response to 1024 bytes but it should be large enough for most cases
	buffer := make([]byte, 1024)
	_, err = response.Body.Read(buffer)
	if err != nil {
		log.Printf("VerifyValues failed reading response")
		return false, "", err
	}

	// Check for ns
	rematch := REVerifyDirectNs.FindSubmatch(buffer)
	if rematch == nil {
		return false, "", errors.New("VerifyValues: ns value not found on the response of the OP")
	}
	nsValue := string(rematch[1])
	if !bytes.Equal([]byte(nsValue), []byte("http://specs.openid.net/auth/2.0")) {
		return false, "", errors.New("VerifyValues: ns value not correct: " + nsValue)
	}

	// Check for is_valid
	match, err := regexp.Match(REVerifyDirectIsValid, buffer)
	if err != nil {
		return false, "", err
	}

	identifier = values.Get("openid.claimed_id")
	if !match {
		log.Printf("no is_valid:true in \"%s\"", buffer)
	}

	return match, identifier, nil
}
示例#4
0
func GetTrendingRepositories(client *http.Client) ([]Repository, os.Error) {
	resp, e := client.Get("https://www.github.com/explore")
	if e != nil {
		return nil, e
	}
	rootnode, e := html.Parse(resp.Body)
	if e != nil {
		return nil, e
	}

	list := make([]Repository, 0, 5)
	listnode := findNextNodeWithClass(rootnode, "ranked-repositories")
	for _, item := range listnode.Child {
		repo := findNextNodeWithTag(item, "h3")
		if repo != nil && !hasClass("last", item) {
			owner := repo.Child[1].Child[0].Data
			name := repo.Child[3].Child[0].Data
			list = append(list, Repository{
				User: owner,
				Name: name,
			})
		}
	}
	return list, nil

}
示例#5
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
}
示例#6
0
func fetchXMLFeed(url string) string {
	client := http.Client{}
	response, err := client.Get(url)
	if err != nil {
		return ""
	}
	defer response.Body.Close()
	return readAllContents(response.Body)
}
示例#7
0
文件: cstore_test.go 项目: emk/cstore
func assertHttpGetStatus(t *testing.T, client *http.Client, code int, url string) {
	r, err := client.Get(url)
	if err != nil {
		t.Errorf("Can't GET %v: %v", url, err)
		return
	}
	defer r.Body.Close()
	if r.StatusCode != code {
		t.Errorf("Expected status %v, got %v", code, r.Status)
	}
}
示例#8
0
func printNum(i int, c *http.Client, ch chan int) {
	url := fmt.Sprintf("http://www.reddit.com?count=%d", i)
	resp, _ := c.Get(url)
	defer resp.Body.Close()

	readBytes, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("Status: %s, Bytes: %d\n", resp.Status, len(readBytes))
	ch <- 1

	//fmt.Print(byteString(readBytes))
}
示例#9
0
文件: qman.go 项目: ryandotsmith/qman
func sickle_lookup(u, p, q_name string, q *Queue) {
	url := sickleUrl + "/lookup?username="******"&password="******"&queue_name=" + q_name
	client := new(http.Client)
	resp, _, _ := client.Get(url)
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode == 404 {
		fmt.Println("could not find queue")
	}
	json.Unmarshal(body, q)
	return
}
示例#10
0
func PostActivity(activity *Activity, bearerToken string, client *http.Client) {
	outputJSON, _ := json.Marshal(activity)
	request, _ := http.NewRequest("POST", "https://api.runkeeper.com/fitnessActivities", strings.NewReader(string(outputJSON)))
	request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
	request.Header.Add("Content-Type", "application/vnd.com.runkeeper.NewFitnessActivity+json")
	response, _ := client.Do(request)
	if response.StatusCode == 201 {
		fmt.Print("Activity POSTed")
	} else {
		fmt.Printf("Activity post failed with status code %d and message %s", response.StatusCode, response.Body)
	}
}
示例#11
0
// Sign and send a Request using the current configuration.
func (c *UserConfig) send(request *http.Request, service *Service, client *http.Client) (*http.Response, os.Error) {
	if err := service.Sign(request, c); err != nil {
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	if response.StatusCode != 200 {
		return nil, os.NewError("Endpoint response: " + response.Status)
	}
	return response, nil
}
示例#12
0
文件: cstore_test.go 项目: emk/cstore
func assertHttpGet(t *testing.T, client *http.Client, expected, url string) {
	r, err := client.Get(url)
	if err != nil {
		t.Errorf("Can't GET %v: %v", url, err)
		return
	}
	defer r.Body.Close()
	if r.StatusCode != http.StatusOK {
		t.Errorf("Unexpected HTTP status: %v", r.Status)
		return
	}
	assertResponseBody(t, expected, r)
}
func TestIntegration(t *testing.T) {
	service, userConfig := GetTwitterConfig(t)
	httpClient := new(http.Client)
	url := "https://api.twitter.com/1/account/verify_credentials.json"
	httpRequest, _ := http.NewRequest("GET", url, nil)
	service.Sign(httpRequest, userConfig)
	httpResponse, err := httpClient.Do(httpRequest)
	if err != nil {
		t.Error("Response had an error")
	}
	if httpResponse.StatusCode != 200 {
		t.Errorf("Response returned code of %v", httpResponse.StatusCode)
	}
}
示例#14
0
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
}
示例#15
0
/*
récupère la vue d'un troll.
Renvoie des SoapItem pour la compatibilité avec la fonction FetchVueSoap.
Utilise le TksManager pour renseigner le nom du troll qui n'est pas renvoyé par le sp.
Paramètres avecTresors, avecLieux : 0 ou 1
*/
func FetchVueSp(numero uint, mdp_restreint string, avecTresors uint, avecLieux uint, tksManager *TksManager) (items []*SoapItem, errorDetails string) {
	httpClient := new(http.Client)
	request := fmt.Sprintf("http://sp.mountyhall.com/SP_Vue2.php?Numero=%d&Motdepasse=%s&Tresors=%d&Lieux=%d", numero, mdp_restreint, avecTresors, avecLieux)
	resp, err := httpClient.Get(request)
	if err != nil {
		errorDetails = err.String()
		return
	}
	defer resp.Body.Close()
	r := bufio.NewReader(resp.Body)
	bline, _, _ := r.ReadLine()
	line := string(bline)
	currentType := ""
	for line != "" {
		if line[0] == '#' {
			tokens := strings.Split(line, " ", 2)
			if tokens[0] == "#DEBUT" && len(tokens) > 1 {
				currentType = (tokens[1])[0 : len(tokens[1])-1]
			}
		} else {
			tokens := strings.Split(line, ";", 5)
			//fmt.Printf(" %s %+v\n", currentType, tokens)
			item := new(SoapItem)
			item.Numero, _ = strconv.Atoi(tokens[0])
			if item.Numero > 0 {
				if currentType == "TROLL" && len(tokens) > 3 {
					item.Nom, _, _ = tksManager.GetNomRaceNiveauTroll(item.Numero)
					item.PositionX, _ = strconv.Atoi(tokens[1])
					item.PositionY, _ = strconv.Atoi(tokens[2])
					item.PositionN, _ = strconv.Atoi(tokens[3])
				} else if len(tokens) > 4 {
					item.Nom = AsciiToUTF8([]uint8(tokens[1]))
					item.PositionX, _ = strconv.Atoi(tokens[2])
					item.PositionY, _ = strconv.Atoi(tokens[3])
					item.PositionN, _ = strconv.Atoi(tokens[4])
				}
				if item.Nom != "" && currentType != "" {
					item.Type = currentType
					items = append(items, item)
				}
			}
		}
		bline, _, _ = r.ReadLine()
		line = string(bline)
	}
	return
}
示例#16
0
func YadisRequest(url_ string, method string) (resp *http.Response, err os.Error) {
	resp = nil

	var request = new(http.Request)
	var client = new(http.Client)
	var Header = make(http.Header)

	request.Method = method
	request.RawURL = url_

	request.URL, err = url.Parse(url_)
	if err != nil {
		return
	}

	// Common parameters
	request.Proto = "HTTP/1.0"
	request.ProtoMajor = 1
	request.ProtoMinor = 0
	request.ContentLength = 0
	request.Close = true

	Header.Add("Accept", "application/xrds+xml")
	request.Header = Header

	// Follow a maximum of 5 redirections
	for i := 0; i < 5; i++ {
		response, err := client.Do(request)

		if err != nil {
			return nil, err
		}
		if response.StatusCode == 301 || response.StatusCode == 302 || response.StatusCode == 303 || response.StatusCode == 307 {
			location := response.Header.Get("Location")
			request.RawURL = location
			request.URL, err = url.Parse(location)
			if err != nil {
				return
			}
		} else {
			return response, nil
		}
	}
	return nil, os.NewError("Too many redirections")
}
示例#17
0
func NewStream(username, password string) (*RawStream, os.Error) {
	var s = &RawStream{Updates: make(chan Update, 100)}
	client := new(http.Client)
	req, _ := http.NewRequest("GET", FEED_URL, nil)
	req.SetBasicAuth(username, password)
	if res, err := client.Do(req); err == nil {
		if res.StatusCode == 200 {
			s.body = res.Body
			go s.process()
		} else {
			return nil, os.NewError(res.Status)
		}
	} else {
		return nil, err
	}

	return s, nil
}
示例#18
0
文件: godns.go 项目: manveru/godns
func nmcPOST(body *bytes.Buffer) (response *http.Response, err os.Error) {
	client := http.Client{}

	var req http.Request
	req.Method = "POST"
	req.ProtoMajor = 1
	req.ProtoMinor = 1
	req.Close = true
	req.Body = ioutil.NopCloser(body)
	req.Header = http.Header{
		"Content-Type":   []string{"text/plain"},
		"Content-Length": []string{strconv.Itoa(body.Len())},
	}
	req.ContentLength = int64(body.Len())
	req.URL = options.nmcURL

	return client.Do(&req)
}
示例#19
0
func main() {
	logger := cabin.New()
	client := new(http.Client)
	response, error := client.Get("http://www.google.com/")
	if error != nil {
		logger.Log(error)
		return
	}

	channel := make(chan *cabin.Event)
	logger.Subscribe(channel)
	go JSONLogger(channel)

	//logger.Log(response)
	//logger.Log("Hello world")
	logger.Log(response.Header)
	//logger.Log(&cabin.Event{Message: "Hello world", Object: response})
}
示例#20
0
func main() {
	c := http.Client{}
	url := "http://127.0.0.1:8080/newtask"
	data := map[string]string{
		"type": "MD5",
		"hash": "5ebe2294ecd0e0f08eab7690d2a6ee69",
	}

	req, err := c.PostForm(url, data)

	if err == nil {
		body, _ := ioutil.ReadAll(req.Body)
		fmt.Printf("%s\n", body)
		req.Body.Close()
	} else {
		fmt.Printf("Error: %v\n", err)
	}
	return
}
示例#21
0
func ObtainBearerToken(code string) {
	tokenUrl := "https://runkeeper.com/apps/token"
	formData := make(map[string][]string)
	formData["grant_type"] = []string{"authorization_code"}
	formData["code"] = []string{code}
	formData["client_id"] = []string{ClientId}
	formData["client_secret"] = []string{ClientSecret}
	formData["redirect_uri"] = []string{RedirectUri}
	client := new(http.Client)
	response, err := client.PostForm(tokenUrl, formData)
	responseJson := make(map[string]string)
	if err == nil {
		responseBody, _ := ioutil.ReadAll(response.Body)
		json.Unmarshal(responseBody, &responseJson)
		file, _ := os.Create(".bearer_token")
		file.WriteString(responseJson["access_token"])
		file.Close()
	} else {
		fmt.Print(err)
	}
}
示例#22
0
func (self *Federation) downloadFrontier(rawurl string, blobref string) (frontier []string, err os.Error) {
	// Get the blob
	var client http.Client
	req, err := client.Get(rawurl + "?frontier=" + http.URLEscape(blobref))
	if err != nil {
		return nil, err
	}
	// Process the returned value
	blob, err := ioutil.ReadAll(req.Body)
	if err != nil {
		log.Printf("Error reading request body")
		return nil, err
	}
	req.Body.Close()
	err = json.Unmarshal(blob, &frontier)
	if err != nil {
		log.Printf("Malformed frontier response: %v\n", err)
		return nil, err
	}
	return
}
示例#23
0
func handler(w http.ResponseWriter, req *http.Request) {
	out := io.Writer(w)
	_ = time.LocalTime()
	_ = strings.HasPrefix("a", "b")
	if strings.HasSuffix(req.URL.Path, "stream.php") {
		log.Print("Found stream.php")
		filename := "stream-" + time.LocalTime().String() + ".mp3"
		f, e := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
		if e != nil {
			log.Print("Could not open: ", filename)
			return
		}
		defer f.Close()

		out = &TeeWriter{
			w,
			f,
		}
	}
	c := http.Client{}
	resp, e := c.Do(req)
	if e != nil {
		log.Print("Could not get site: ", e)
		return
	}
	defer resp.Body.Close()

	for key, vals := range resp.Header {
		for _, val := range vals {
			w.Header().Add(key, val)
		}
	}

	_, e = io.Copy(out, resp.Body)
	if e != nil {
		log.Print("Error while sending data: ", e)
		return
	}
}
示例#24
0
func TestHelloWorld(t *testing.T) {
	stack := new(Stack)
	testServer := httptest.NewServer(stack.HandlerFunc(helloWorld))
	defer testServer.Close()

	var client = http.Client{}

	// Request against it
	response, err := client.Get(testServer.URL)

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

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

	body, _ := ioutil.ReadAll(response.Body)
	if string(body) != "Hello World!" {
		t.Error("Expected body:", string(body), "to equal: \"Hello World!\"")
	}
}
示例#25
0
func GetSoapEnvelope(query string, numero uint, mdp string) (envelope *SoapEnvelope) {
	httpClient := new(http.Client)
	soapRequestContent := fmt.Sprintf(query, numero, mdp)

	resp, err := httpClient.Post(MH_SOAP_URL, "text/xml; charset=utf-8", bytes.NewBufferString(soapRequestContent))

	if err != nil {
		fmt.Println("Erreur : " + err.String())
		return nil
	}
	// là on fait du lourd : on passe par une chaine car j'ai pas le temps ce soir de trouver comment sauter directement un bout du flux jusqu'au début du xml
	b, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		fmt.Println("Erreur lecture :")
		fmt.Println(e)
	}
	in := string(b)
	indexDebutXml := strings.Index(in, "<?xml version")
	if indexDebutXml > 0 {
		fmt.Printf("Erreur message SOAP. Début XML à l'index %d\n", indexDebutXml)
		in = in[indexDebutXml:len(in)]
	}
	//fmt.Print(in)
	parser := xml.NewParser(bytes.NewBufferString(in))
	parser.CharsetReader = CharsetReader
	envelope = new(SoapEnvelope)
	err = parser.Unmarshal(&envelope, nil)
	if err != nil {
		fmt.Println("Erreur au décodage du XML : " + err.String())
		return nil
	}

	resp.Body.Close()

	return
}
示例#26
0
func (nc *Client) request(path string, data url.Values) (*response, os.Error) {
	// endpoint
	url := "https://api.notifo.com/v1" + path
	// encode request params
	reqBody := strings.NewReader(data.Encode())
	// build request
	req, err := http.NewRequest("POST", url, reqBody)
	if err != nil {
		return nil, err
	}
	req.Method = "POST"
	req.SetBasicAuth(nc.Username, nc.ApiSecret)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	// make request
	client := new(http.Client)
	r, err := client.Do(req)
	// check connection
	if err != nil {
		return nil, err
	}
	defer r.Body.Close()
	// read response
	body, _ := ioutil.ReadAll(r.Body)
	// decode json
	response := new(response)
	err = json.Unmarshal(body, &response)
	if err != nil {
		return nil, err
	}
	// check for success code
	if response.Code != 2201 {
		return nil, fmt.Errorf("notifo: %s", response.Message)
	}
	// no error
	return response, nil
}
示例#27
0
	escaped := new(bytes.Buffer)
	template.HTMLEscape(escaped, raw)
	rendered := blackfriday.Markdown(escaped.Bytes(), renderer, extensions)
	enabled := true
	fmt.Println("Raw message:")
	fmt.Println(string(raw))
	if enabled {
		fmt.Println("Rendered message:")
		fmt.Println(string(rendered))
		return rendered
	}
	return raw
}

var GetEmbed = func() func(string) (string, bool) {
	client := new(http.Client)
	key := "83518a4c0f8f11e186fe4040d3dc5c07"
	templateString := "http://api.embed.ly/1/oembed?key=" + key + "&url=%s" + "&maxwidth=800"
	return func(url string) (string, bool) {
		requestUrl := fmt.Sprintf(templateString, url)
		res, err := client.Get(requestUrl)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error in GetEmbed: %s\n", err)
			return "", false
		}
		defer res.Body.Close()
		contents, err := ioutil.ReadAll(res.Body)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error in GetEmbed 2: %s\n", err)
			return "", false
		}
示例#28
0
func fetchRunList(client *http.Client, url string) *PlusService {
	response, _ := client.Get(url)
	ps := new(PlusService)
	xml.Unmarshal(response.Body, ps)
	return ps
}