예제 #1
0
func handleDeleteForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	_, kind := path.Split(r.URL.Path)
	key := DefaultMaster.delegator.(DelegatorBroadcaster).KeyFromForm(r.Form)
	ser := DefaultMaster.delegator.Delegate(kind)
	keys := ser.Keys()
	n := ser.Init()
	for _, v := range keys {
		if v != key {
			n = n.Insert(ser.At(v))
		}
	}
	ser.All(n)
	s := ser.At(key).(SerialSender)
	DefaultMaster.Delete(s)
	out := bytes.NewBufferString("")
	host := s.Host()
	if host != "" {
		DefaultMaster.save(out, s)
		http.Post("http://"+host+DefaultMaster.deletePattern+kind, "application/octet-stream", out)
	} else {
		bc := DefaultMaster.delegator.(DelegatorBroadcaster)
		for _, h := range bc.Hosts() {
			out = bytes.NewBufferString("")
			DefaultMaster.save(out, s)
			http.Post("http://"+h+DefaultMaster.deletePattern+kind, "application/octet-stream", out)
		}
	}
	DefaultMaster.Logger.Printf("%v erfolgreich gelöscht", s.Log())
	redir := "http://" + r.Host + r.FormValue("Redir")
	w.SetHeader("Location", redir)
	w.WriteHeader(302)
}
예제 #2
0
func handleReplaceForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	_, kind := path.Split(r.URL.Path)
	ser := DefaultMaster.delegator.Delegate(kind).(SerializerFormParser)
	s := ser.NewFromForm(r.Form)
	if s == nil {
		r.Form = nil
		w.SetHeader("Location", r.Referer)
		w.WriteHeader(302)
		return
	}
	ser.Replace(s)
	DefaultMaster.Save(s)
	out := bytes.NewBufferString("")
	host := s.Host()
	if host != "" {
		DefaultMaster.save(out, s)
		http.Post("http://"+host+DefaultMaster.replacePattern+kind, "application/octet-stream", out)
	} else {
		bc := DefaultMaster.delegator.(DelegatorBroadcaster)
		for _, h := range bc.Hosts() {
			out = bytes.NewBufferString("")
			DefaultMaster.save(out, s)
			http.Post("http://"+h+DefaultMaster.replacePattern+kind, "application/octet-stream", out)
		}
	}
	DefaultMaster.Logger.Printf("%v erfolgreich modifiziert", s.Log())
	redir := "http://" + r.Host + r.FormValue("Redir")
	w.SetHeader("Location", redir)
	w.WriteHeader(302)
}
예제 #3
0
func main() {
	flag.Parse()

	listener, err := net.Listen("tcp", *listenAddr)
	if err != nil {
		panic(err)
	}

	conn, err := listener.Accept()
	if err != nil {
		panic(err)
	}

	buf := new(bytes.Buffer)

	// initiate new session and read key
	log.Stderr("Attempting connect", *destAddr)
	buf.Write([]byte(*destAddr))
	resp, err := http.Post(
		"http://"+*httpAddr+"/create",
		"text/plain",
		buf)
	if err != nil {
		panic(err)
	}
	key, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	log.Stderr("Connected, key", key)

	// ticker to set a rate at which to hit the server
	tick := time.NewTicker(int64(*tickInterval) * 1e6)
	read := makeReadChan(conn, bufSize)
	buf.Reset()
	for {
		select {
		case <-tick.C:
			// write buf to new http request
			req := bytes.NewBuffer(key)
			buf.WriteTo(req)
			resp, err := http.Post(
				"http://"+*httpAddr+"/ping",
				"application/octet-stream",
				req)
			if err != nil {
				log.Stderr(err.String())
				continue
			}
			// write http response response to conn
			io.Copy(conn, resp.Body)
			resp.Body.Close()
		case b := <-read:
			buf.Write(b)
		}
	}
}
예제 #4
0
파일: now.go 프로젝트: alloy-d/now.go
func pop() {
	_, err := http.Post("http://"+*addr+"/done", "text/plain", strings.NewReader("done"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "http.Post: %v", err)
		os.Exit(1)
	}
}
예제 #5
0
파일: get.go 프로젝트: go-nosql/golang
func main() {
	flag.Parse()
	if *addr {
		l, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			log.Fatal(err)
		}
		defer l.Close()
		fmt.Print(l.Addr())
		return
	}
	url := flag.Arg(0)
	if url == "" {
		log.Fatal("no url supplied")
	}
	var r *http.Response
	var err os.Error
	if *post != "" {
		b := strings.NewReader(*post)
		r, err = http.Post(url, "application/x-www-form-urlencoded", b)
	} else {
		r, err = http.Get(url)
	}
	if err != nil {
		log.Fatal(err)
	}
	defer r.Body.Close()
	_, err = io.Copy(os.Stdout, r.Body)
	if err != nil {
		log.Fatal(err)
	}
}
예제 #6
0
func tmp() {
	data, err := json.Marshal(map[string]interface{}{
		"method": "getinfo",
		"id":     1,
		"params": []interface{}{},
	})
	if err != nil {
		log.Fatalf("Marshal: %v", err)
	}
	resp, err := http.Post("http://*****:*****@127.0.0.1:8332",
		"application/json", strings.NewReader(string(data)))
	if err != nil {
		log.Fatalf("Post: %v", err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("ReadAll: %v", err)
	}
	result := make(map[string]interface{})
	err = json.Unmarshal(body, &result)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}
	log.Println(result)
}
예제 #7
0
func (c *Client) StatusesUpdate(status string, replyId uint64) (err os.Error) {
	var params string

	if status == "" {
		return os.NewError("must need \"status\" parameter.")
	}

	params = addParam(params, "status", http.URLEscape(status))

	if replyId != 0 {
		params = addParam(params, "in_reply_to_status_id", fmt.Sprintf("%d", replyId))
	}

	url := c.makeAuthURL(statusesUpdate, params)
	res, err := http.Post(url, "", bytes.NewBufferString(""))
	if err != nil {
		return err
	}

	if res.Status != "200 OK" {
		return os.NewError("Request failed")
	}

	return nil
}
예제 #8
0
func Verify(r *http.Request) string {

	if err := r.ParseForm(); err != nil {
		return "Anonymous"
	}

	token := r.FormValue("assertion")
	url := "https://browserid.org/verify"
	bodytype := "application/x-www-form-urlencoded"
	body := strings.NewReader("assertion=" + token + "&audience=" + r.Host)

	var response_body []byte
	res, err := http.Post(url, bodytype, body)
	if err != nil {
		fmt.Println("err=", err)
		return "Anonymous"
	} else {
		response_body, _ = ioutil.ReadAll(res.Body)
		res.Body.Close()
	}

	var f interface{}
	json.Unmarshal(response_body, &f)

	m := f.(map[string]interface{})
	return fmt.Sprintf("%s", m["email"])
}
func Call(address string, method string, id interface{}, params []interface{}) (map[string]interface{}, os.Error) {
	data, err := json.Marshal(map[string]interface{}{
		"method": method,
		"id":     id,
		"params": params,
	})
	if err != nil {
		log.Fatalf("Marshal: %v", err)
		return nil, err
	}
	resp, err := http.Post(address,
		"application/json", strings.NewReader(string(data)))
	if err != nil {
		log.Fatalf("Post: %v", err)
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("ReadAll: %v", err)
		return nil, err
	}
	result := make(map[string]interface{})
	err = json.Unmarshal(body, &result)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
		return nil, err
	}
	//log.Println(result)
	return result, nil
}
예제 #10
0
func ShortenURL(longUrl string) (shortenUrl string, err os.Error) {
	var encbuf bytes.Buffer
	enc := json.NewEncoder(&encbuf)
	err = enc.Encode(map[string]string{"longUrl": longUrl})
	if err != nil {
		return
	}
	res, err := http.Post("https://www.googleapis.com/urlshortener/v1/url", "application/json", strings.NewReader(encbuf.String()))
	if err != nil {
		return
	}
	if res.StatusCode != 200 {
		err = os.NewError("failed to post")
		return
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	var decbuf bytes.Buffer
	decbuf.Write(b)
	dec := json.NewDecoder(&decbuf)
	var out map[string]interface{}
	err = dec.Decode(&out)
	if err != nil {
		return
	}
	shortenUrl = out["id"].(string)
	return
}
예제 #11
0
func (c *Client) FriendshipsCreate(userId uint64, screenName string, follow bool) (err os.Error) {
	var params string

	if userId != 0 {
		params = addParam(params, "user_id", fmt.Sprintf("%d", userId))
	}
	if screenName != "" {
		params = addParam(params, "screen_name", screenName)
	}
	if follow == true {
		params = addParam(params, "follow", "true")
	}

	url := c.makeAuthURL(friendshipsCreate, params)
	res, err := http.Post(url, "", bytes.NewBufferString(""))
	if err != nil {
		return err
	}

	if res.Status != "200 OK" {
		return os.NewError("Request failed.")
	}

	return nil
}
예제 #12
0
파일: oauth.go 프로젝트: adamsxu/twister
func (c *Client) request(client *http.Client, credentials *Credentials, urlStr string, param web.Values) (*Credentials, web.Values, os.Error) {
	c.SignParam(credentials, "POST", urlStr, param)
	resp, err := http.Post(urlStr, "application/x-www-form-urlencoded", bytes.NewBuffer(param.FormEncodedBytes()))
	if err != nil {
		return nil, nil, err
	}
	p, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return nil, nil, err
	}
	if resp.StatusCode != 200 {
		return nil, nil, os.NewError(fmt.Sprintf("OAuth server status %d, %s", resp.StatusCode, string(p)))
	}
	m := make(web.Values)
	err = m.ParseFormEncodedBytes(p)
	if err != nil {
		return nil, nil, err
	}
	credentials = &Credentials{Token: m.Get("oauth_token"), Secret: m.Get("oauth_token_secret")}
	if credentials.Token == "" {
		return nil, nil, os.NewError("No OAuth token in server result")
	}
	if credentials.Secret == "" {
		return nil, nil, os.NewError("No OAuth secret in server result")
	}
	return credentials, m, nil
}
예제 #13
0
func handleInsertForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	_, kind := path.Split(r.URL.Path)
	ser := DefaultMaster.delegator.Delegate(kind).(SerializerFormParser)
	s := ser.NewFromForm(r.Form)
	if s == nil {
		r.Form = nil
		w.SetHeader("Location", r.Referer)
		w.WriteHeader(302)
		return
	}
	ser.All(ser.Insert(s))
	err := DefaultMaster.Save(s)
	if err != nil {
		DefaultMaster.Logger.Printf("Problem: Einfügen von %s auf Hauptserver fehlgeschlagen", s.Log())
		w.WriteHeader(500)
	}
	out := bytes.NewBufferString("")
	out = bytes.NewBufferString("")
	DefaultMaster.save(out, s)

	host := s.Host()
	switch host {
	case "":
		bc := DefaultMaster.delegator.(DelegatorBroadcaster)
		for _, h := range bc.Hosts() {
			resp, err := http.Post("http://"+h+DefaultMaster.insertPattern+kind, "application/octet-stream", out)
			if resp.StatusCode == 500 || err != nil {
				DefaultMaster.Logger.Printf("Problem: Einfügen von %s auf Server %s fehlgeschlagen", s.Log(), h)
			}
		}
	case "NO":
		break
	default:
		resp, err := http.Post("http://"+host+DefaultMaster.insertPattern+kind, "application/octet-stream", out)
		if resp.StatusCode == 500 || err != nil {
			DefaultMaster.Logger.Printf("Problem: Einfügen von %s auf Server %s fehlgeschlagen", s.Log(), host)
		}
	}
	DefaultMaster.Logger.Printf("%v erfolgreich angelegt", s.Log())
	redir := "http://" + r.Host + r.FormValue("Redir") + strconv.Itoa(s.Key())
	w.SetHeader("Location", redir)
	w.WriteHeader(302)
}
예제 #14
0
파일: comm.go 프로젝트: skelterjohn/sao
func SendChanClient(host, id string) (send chan<- string) {
	sendc := make(chan string)
	send = sendc
	url := fmt.Sprintf("http://%s/%s/Send", host, id)
	go func() {
		for message := range sendc {
			http.Post(url, "text/plain", bytes.NewBufferString("msg="+message))
		}
	}()
	return
}
예제 #15
0
// maybeReportToDashboard reports path to dashboard unless
// -dashboard=false is on command line.  It ignores errors.
func maybeReportToDashboard(path string) {
	// if -dashboard=false was on command line, do nothing
	if !*reportToDashboard {
		return
	}

	// otherwise lob url to dashboard
	r, _ := http.Post(dashboardURL, "application/x-www-form-urlencoded", strings.NewReader("path="+path))
	if r != nil && r.Body != nil {
		r.Body.Close()
	}
}
예제 #16
0
파일: later.go 프로젝트: alloy-d/now.go
func addThing(thing string) {
	path := "/later/"
	if *first {
		path = "/now"
	}

	_, err := http.Post("http://"+*addr+path, "text/plain", strings.NewReader("thing="+thing))
	if err != nil {
		fmt.Fprintf(os.Stderr, "http.Post: %v", err)
		os.Exit(1)
	}
}
예제 #17
0
func (p *THttpClient) Flush() os.Error {
	response, err := http.Post(p.url.String(), "application/x-thrift", p.requestBuffer)
	if err != nil {
		return NewTTransportExceptionFromOsError(err)
	}
	if response.StatusCode != http.StatusOK {
		// TODO(pomack) log bad response
		return NewTTransportException(UNKNOWN_TRANSPORT_EXCEPTION, "HTTP Response code: "+string(response.StatusCode))
	}
	p.response = response
	return nil
}
예제 #18
0
func TestCapabilities(t *testing.T) {
	go setupRobot()
	time.Sleep(2e8)

	body := bytes.NewBufferString(test_req)
	resp, _ := http.Post(
		"http://127.0.0.1:8080/_wave/robot/jsonrpc",
		"text/json",
		body)
	respBody, _ := ioutil.ReadAll(resp.Body)
	if string(respBody) != test_resp {
		t.Error("Response body not as expected.")
	}
}
예제 #19
0
func main() {
	url := "http://127.0.0.1:8080/"
	b := strings.NewReader("var1=value1&secondvar=value2")
	//    h := http.Header()
	req, err := http.Post(url, "application/x-www-form-urlencoded", b)

	if err == nil {
		body, _ := ioutil.ReadAll(req.Body)
		fmt.Printf("%s\n", body)
		req.Body.Close()
	} else {
		fmt.Printf("Error: %v\n", err)
	}
	return
}
예제 #20
0
func main() {
	response, err := http.Post(url, "text/plain", os.Stdin)
	if err != nil {
		panic("http post fail: " + err.String())
	}
	defer response.Body.Close()
	_, err = ioutil.ReadAll(response.Body)
	if err != nil {
		panic("http post fail: " + err.String())
	}
	if response.StatusCode == 200 {
		println("groovy!")
	} else {
		println("hrm.. \"" + response.Status + "\"")
	}
}
예제 #21
0
func main() {
	url := "http://127.0.0.1:8080/"
	b := strings.NewReader(`{"key":"value"}`)
	//h := http.Header{}
	//h.Add("ContentLength", "10")
	req, err := http.Post(url, "application/json", b)

	if err == nil {
		body, _ := ioutil.ReadAll(req.Body)
		req.Body.Close()
		fmt.Printf("Body: %s\n", body)
	} else {
		fmt.Printf("Error: %v\n", err)
	}
	return
}
예제 #22
0
// Do an authenticated Post if we've called Authenticated, otherwise
// just Post it without authentication
func httpPost(url, user, pass, client, clientURL, version, agent,
	data string) (*http.Response, os.Error) {
	var r *http.Response
	var err os.Error

	body := bytes.NewBufferString(data)
	bodyType := "application/x-www-form-urlencoded"

	if user != "" && pass != "" {
		r, err = authPost(url, user, pass, client, clientURL,
			version, agent, bodyType, body)
	} else {
		r, err = http.Post(url, bodyType, body)
	}

	return r, err
}
예제 #23
0
func (c *Client) StatusesRetweet(id uint64) (err os.Error) {
	if id == 0 {
		return os.NewError("must need \"id\" parameter.")
	}

	url := c.makeAuthURL(statusesRetweet+fmt.Sprintf("/%d", id), "")
	res, err := http.Post(url, "", bytes.NewBufferString(""))
	if err != nil {
		return err
	}

	if res.Status != "200 OK" {
		return os.NewError("Request failed")
	}

	return nil
}
예제 #24
0
파일: googl.go 프로젝트: kaimallea/go-googl
/**
 * Shorten a long url
 *
 */
func shortenUrl(url string) (string, string) {
	payload := strings.NewReader("{\"longUrl\": \"" + url + "\"}")

	res, err := http.Post(shorten_endpoint, "application/json", payload)
	if err != nil {
		fmt.Printf("%s\n\r", err)
		return "", url
	}

	var jsonresult map[string]string

	body, _ := ioutil.ReadAll(res.Body)
	if json.Unmarshal(body, &jsonresult) != nil {
		fmt.Printf("Error processing %s\n\r", url)
		return "", url
	}

	res.Body.Close()

	return jsonresult["id"], url
}
예제 #25
0
파일: googl.go 프로젝트: mcspring/googl.go
func (req *Googl) post(url string) (string, os.Error) {
	if strings.Contains(url, "://goo.gl/") {
		return fmt.Sprintf("{\n \"kind\": \"urlshortener#url\",\n \"id\": \"%s\",\n \"longUrl\": \"%s\"\n}", url, url), nil
	}

	req_url := GOOGL_V1
	if "" != req.Key {
		req_url += "?key=" + req.Key
	}

	buf := bytes.NewBuffer(nil)
	buf.WriteString(fmt.Sprintf(`{"longUrl": "%s"}`, url))

	res, err := http.Post(req_url, "application/json", buf)
	if err != nil {
		return "", os.Error(err)
	}

	body, _ := ioutil.ReadAll(res.Body)

	return string(body), nil
}
예제 #26
0
파일: rdio.go 프로젝트: natelong/playlistr
func RequestFromService(method string, apiParams map[string]string) string {
	log.Printf("Requsting %s method", method)

	params := make(map[string]string)
	params["method"] = method
	for key, val := range apiParams {
		params[key] = val
	}

	signature := easyauth.GenerateSignature(
		apiUrl,
		easyauth.POST,
		clientId,
		clientSecret,
		params,
	)

	params["oauth_signature"] = easyauth.UrlEncode(signature)
	fullParams := easyauth.GetOrderedParamString(params)

	response, err := http.Post(
		apiUrl,
		"application/x-www-form-urlencoded",
		strings.NewReader(fullParams),
	)
	if err != nil {
		log.Panic("Couldn't send URL Request")
	}

	log.Printf("Response from API: %s", response.Status)

	apiResponse := make([]byte, response.ContentLength)
	_, err = io.ReadFull(response.Body, apiResponse)
	if err != nil {
		log.Panic("Couldn't read response from service")
	}
	return string(apiResponse)
}
예제 #27
0
파일: test.go 프로젝트: appaquet/gostore
func writeTest(start int, requests int, end chan bool) {
	for i := 0; i < requests; i++ {

		server := randomServer()
		url := fmt.Sprintf("http://%s/home%d/nitro%d?size=%d", server, start+i, start+requests-i, len(data))
		buf := bytes.NewBuffer(data)

		startTime := time.Nanoseconds()
		r, err := http.Post(url, "application/json", buf)
		if err != nil {
			fmt.Printf("ERROR: Posting error: %s\n", err)
		} else {
			ioutil.ReadAll(r.Body)
		}
		elapsed := time.Nanoseconds() - startTime

		mutex.Lock()
		elapsedSum += float64(elapsed) / 1000000
		requestsSum++
		mutex.Unlock()
	}

	end <- true
}