Golang PostForm示例

说明

golang postform示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: crawl.go 项目: bgpat/autocai

func crawl(exe_dir string, db *sql.DB) {
	res, _ := http.PostForm("http://shirodanuki.cs.shinshu-u.ac.jp/cgi-bin/olts/sys/exercise.cgi",
		url.Values{
			"name":    {"hoge"},
			"id":      {"hogehoge"},
			"email":   {""},
			"exe_dir": {exe_dir},
			"chapter": {""},
			"url":     {"http://webmizar.cs.shinshu-u.ac.jp/learn/infomath/"},
		},
	)
	defer res.Body.Close()
	utf8 := euc2utf8(res.Body)
	doc, _ := goquery.NewDocumentFromReader(utf8)
	html, _ := doc.Find("blockquote").Html()
	question := strings.TrimSpace(html)
	tmp, _ := doc.Find("input[name=tmp]").Attr("value")
	res, _ = http.PostForm("http://shirodanuki.cs.shinshu-u.ac.jp/cgi-bin/olts/sys/answer.cgi",
		url.Values{
			"answer":  {""},
			"subject": {""},
			"chapter": {""},
			"url":     {"http://webmizar.cs.shinshu-u.ac.jp/learn/infomath/"},
			"tmp":     {tmp},
		},
	)
	defer res.Body.Close()
	utf8 = euc2utf8(res.Body)
	doc, _ = goquery.NewDocumentFromReader(utf8)
	answer := strings.TrimSpace(doc.Find("blockquote tt b").Text())
	stmt, _ := db.Prepare("INSERT INTO `cai` (`exe_dir`, `question`, `answer`) VALUES (?, ?, ?)")
	stmt.Exec(exe_dir, question, answer)
}

示例#2
文件: server_test.go 项目: cocaine/cocaine-flow

func BTestAuth(t *testing.T) {

	ts := httptest.NewServer(ConstructHandler())
	defer ts.Close()

	uv := url.Values{}
	uv.Set("name", testUser)
	uv.Set("password", testUserPasswd)

	r, err := http.PostForm(ts.URL+"/flow/v1/users/signup", uv)
	if err != nil {
		t.Fatal(err)
	}
	if r.StatusCode != 200 {
		defer r.Body.Close()
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		t.Fatal(r.StatusCode, string(body))
	}

	r, err = http.PostForm(ts.URL+"/flow/v1/users/signin", uv)
	if err != nil {
		t.Fatal(err)
	}
	if r.StatusCode != 200 {
		defer r.Body.Close()
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		t.Fatal(r.StatusCode, string(body))
	}
}

示例#3
文件: login_test.go 项目: gooops/gologin

func TestWebHandler_InvalidFields(t *testing.T) {
	config := &Config{
		ConsumerKey: testConsumerKey,
	}
	handler := LoginHandler(config, testutils.AssertSuccessNotCalled(t), nil)
	ts := httptest.NewServer(ctxh.NewHandler(handler))

	// assert errors occur for different missing/incorrect POST fields
	resp, err := http.PostForm(ts.URL, url.Values{"wrongKeyName": {testAccountEndpoint}, accountRequestHeaderField: {testAccountRequestHeader}})
	assert.Nil(t, err)
	testutils.AssertBodyString(t, resp.Body, ErrMissingAccountEndpoint.Error()+"\n")

	resp, err = http.PostForm(ts.URL, url.Values{accountEndpointField: {"https://evil.com"}, accountRequestHeaderField: {testAccountRequestHeader}})
	assert.Nil(t, err)
	testutils.AssertBodyString(t, resp.Body, ErrInvalidDigitsEndpoint.Error()+"\n")

	resp, err = http.PostForm(ts.URL, url.Values{accountEndpointField: {testAccountEndpoint}, accountRequestHeaderField: {`OAuth oauth_consumer_key="notmyconsumerkey",`}})
	assert.Nil(t, err)
	testutils.AssertBodyString(t, resp.Body, ErrInvalidConsumerKey.Error()+"\n")

	// valid, but incorrect Digits account endpoint
	resp, err = http.PostForm(ts.URL, url.Values{accountEndpointField: {"https://api.digits.com/1.1/wrong.json"}, accountRequestHeaderField: {testAccountRequestHeader}})
	assert.Nil(t, err)
	testutils.AssertBodyString(t, resp.Body, ErrUnableToGetDigitsAccount.Error()+"\n")
}

示例#4
文件: weekCheck.go 项目: toyosge/weekTweetBot_Go

func postMessage() {
	resp, err := http.PostForm(
		"https://typetalk.in/oauth2/access_token",
		url.Values{
			"client_id":     {clientId},
			"client_secret": {clientSecret},
			"grant_type":    {"client_credentials"},
			"scope":         {"topic.post"}})
	if err != nil {
		panic(err)
	}
	var d Auth
	err = json.NewDecoder(resp.Body).Decode(&d)
	if err != nil {
		panic(err)
	}
	resp, err = http.PostForm(
		fmt.Sprintf("https://typetalk.in/api/v1/topics/%s", topicId),
		url.Values{
			"access_token": {d.AccessToken},
			"message":      {message}})
	if err != nil {
		panic(err)
	}
}

示例#5
文件: main.go 项目: jimmy-go/spagen

func main() {
	flag.Parse()
	version := time.Now().UTC().Format(time.RFC3339)
	tpl := `<!DOCTYPE html><html><head><title>Sample</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name=viewport content="width=device-width, initial-scale=1"><link rel="shortcut icon" href="favicon.ico"></head><style>%s</style><body>%s</body><script>%s</script><script>$(document).foundation();</script><!-- Version: %s --></html>`
	tpl = strings.Replace(tpl, "\n", "", -1)
	tpl = strings.Replace(tpl, "\t", "", -1)
	os.Remove(*out)
	f, err := os.OpenFile(*out, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	bjs, err := loadDataFromDir(*jspath)
	if err != nil {
		panic(err)
	}
	if *minify {
		resp, err := http.PostForm(jsMinURL, url.Values{"input": []string{string(bjs)}})
		if err != nil {
			log.Printf("main : err [%s]", err)
		} else {
			defer resp.Body.Close()
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				log.Printf("main : err [%s]", err)
			} else {
				bjs = body
			}
		}
	}
	bcss, err := loadDataFromDir(*csspath)
	if err != nil {
		panic(err)
	}
	if *minify {
		rescss, err := http.PostForm(cssMinURL, url.Values{"input": []string{string(bcss)}})
		if err != nil {
			log.Printf("main : err [%s]", err)
		} else {
			defer rescss.Body.Close()
			body, err := ioutil.ReadAll(rescss.Body)
			if err != nil {
				log.Printf("main : err [%s]", err)
			} else {
				bcss = body
			}
		}
	}
	bhtml, err := loadDataFromDir(*htmlpath)
	if err != nil {
		panic(err)
	}
	btpl := []byte(fmt.Sprintf(tpl, string(bcss), string(bhtml), string(bjs), version))
	_, err = f.Write(btpl)
	if err != nil {
		panic(err)
	}
	log.Printf("version generated [%s]", version)
}

示例#6
文件: volume_service_test.go 项目: APTrust/exchange

func TestReport(t *testing.T) {
	if testutil.RunningInCI() {
		t.Skip("Skipping volume service test because it looks like we're in the CI environment.")
	}
	runService(t)

	// Reserve a chunk of space with 8000 bytes
	reserveUrl := fmt.Sprintf("%s/reserve/", serviceUrl)
	params := url.Values{
		"path":  {"/tmp/some_file"},
		"bytes": {"8000"},
	}
	resp, err := http.PostForm(reserveUrl, params)
	require.Nil(t, err)
	data, err := ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	resp.Body.Close()
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	// Reserve another chunk with 24000 bytes
	params = url.Values{
		"path":  {"/tmp/some_other_file"},
		"bytes": {"24000"},
	}
	resp, err = http.PostForm(reserveUrl, params)
	require.Nil(t, err)
	data, err = ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	resp.Body.Close()
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	reportUrl := fmt.Sprintf("%s/report/", serviceUrl)
	resp, err = http.Get(reportUrl)
	require.Nil(t, err)
	data, err = ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	resp.Body.Close()

	expected := `{"Succeeded":false,"ErrorMessage":"Param 'path' is required.","Data":null}`
	assert.Equal(t, expected, string(data))
	assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

	reportUrl = fmt.Sprintf("%s/report/?path=/", serviceUrl)
	resp, err = http.Get(reportUrl)
	require.Nil(t, err)
	data, err = ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	resp.Body.Close()

	expected = `{"Succeeded":true,"ErrorMessage":"","Data":{"/tmp/some_file":8000,"/tmp/some_other_file":24000}}`
	assert.Equal(t, expected, string(data))
	assert.Equal(t, http.StatusOK, resp.StatusCode)
}

示例#7
文件: powersurge.go 项目: scoop/powersurge

func RestartRouter() {
	vals := []string{"0", "1"}

	http.PostForm(fmt.Sprintf("http://%s/login.html", *strip),
		url.Values{"pw": {*password}})
	for _, i := range vals {
		http.PostForm(fmt.Sprintf("http://%s/", *strip),
			url.Values{fmt.Sprintf("cte%d", *socket): {i}})
		time.Sleep(3 * time.Second)
	}
	log.Print("Router is powering back up.")
}

示例#8
文件: 2016-02-18_18.26.43.aeiou.go 项目: mwcm/sublime

// do this in a goroutine so that slow servers don't take us down (see above go work())
func work() {

	messagesProcessed := 0
	totalMessages := 0

	for {

		klass, notClosed := <-messageChannel

		if notClosed && klass != "waiting" {

			fmt.Println(klass)

			switch klass {

			case "foo":
				resp, _ := http.PostForm("http://localhost:5000/", url.Values{"key": {klass}})
				resp.Body.Close()
				messagesProcessed++
				fmt.Println("foo posted")

			case "bar":
				resp, _ := http.PostForm("http://localhost:5000/", url.Values{"key": {klass}})
				resp.Body.Close()
				messagesProcessed++
				fmt.Println("bar posted")

			case "baz":
				resp, _ := http.PostForm("http://localhost:5000/", url.Values{"key": {klass}})
				resp.Body.Close()
				messagesProcessed++
				fmt.Println("baz posted")

			default:
				fmt.Println("ending...")
				i, err := strconv.Atoi(klass)
				if err != nil {
					fmt.Println("whats happening here", err)
				} else {
					totalMessages = i
				}
			}

			if messagesProcessed >= totalMessages && totalMessages != 0 {
				break
			}
		}
	}

	fmt.Println("ALL SHIT SENT !!!!!")
	wg.Done()
}

示例#9
文件: volume_service_test.go 项目: APTrust/exchange

func TestReserve(t *testing.T) {
	if testutil.RunningInCI() {
		t.Skip("Skipping volume service test because it looks like we're in the CI environment.")
	}
	runService(t)

	reserveUrl := fmt.Sprintf("%s/reserve/", serviceUrl)

	// Start with a good request
	params := url.Values{
		"path":  {"/tmp/some_file"},
		"bytes": {"8000"},
	}
	resp, err := http.PostForm(reserveUrl, params)
	require.Nil(t, err)
	data, err := ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	resp.Body.Close()

	expected := `{"Succeeded":true,"ErrorMessage":"","Data":null}`
	assert.Equal(t, expected, string(data))
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	// Bad request: no path
	params = url.Values{
		"bytes": {"8000"},
	}
	resp, err = http.PostForm(reserveUrl, params)
	require.Nil(t, err)
	data, err = ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	resp.Body.Close()

	expected = `{"Succeeded":false,"ErrorMessage":"Param 'path' is required.","Data":null}`
	assert.Equal(t, expected, string(data))
	assert.Equal(t, http.StatusBadRequest, resp.StatusCode)

	// Bad request: no value for bytes
	params = url.Values{
		"path": {"/tmp/some_file"},
	}
	resp, err = http.PostForm(reserveUrl, params)
	require.Nil(t, err)
	data, err = ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	resp.Body.Close()

	expected = `{"Succeeded":false,"ErrorMessage":"Param 'bytes' must be an integer greater than zero.","Data":null}`
	assert.Equal(t, expected, string(data))
	assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}

示例#10
文件: server.go 项目: jonzjia/go-server-bootstrap

func serveCallback(w http.ResponseWriter, r *http.Request) {
	//TODO use oauth library to simplify the following
	log.Print("Clef login")
	vals, err := url.ParseQuery(r.URL.RawQuery)
	if err != nil {
		panic(err)
	}
	code := vals.Get("code")
	v := url.Values{}
	v.Set("code", code)
	v.Set("app_id", APP_ID)
	v.Set("app_secret", APP_SECRET)
	response, err := http.PostForm("https://clef.io/api/authorize", v)

	if err != nil {
		panic(err)
	} else {
		bts, err := ioutil.ReadAll(response.Body)
		if err != nil {
			panic(err)
		}
		result := make(map[string]interface{})
		json.Unmarshal(bts, &result)
		log.Print(result)
		access_token, ok := result["access_token"].(string)
		if !ok {
			log.Print("Something funky happened here: %v", result)
		}

		v := url.Values{}
		v.Set("access_token", access_token)
		response, err := http.PostForm("https://clef.io/api/info", v)
		if err != nil {
			panic(err)
		}
		bts, err = ioutil.ReadAll(response.Body)
		if err != nil {
			panic(err)
		}
		err = json.Unmarshal(bts, &result)
		log.Printf("Result: %v", result)

		session, _ := store.Get(r, PROFILE_SESSION)
		//session.Values["userid"] = access_token
		session.Values["access_token"] = access_token
		session.Save(r, w)

		//http.StatusFound is just an integer, so you can specify 302 directly
		http.Redirect(w, r, "/profile", http.StatusFound)
	}
}

示例#11
文件: token_test.go 项目: gooops/gologin

func TestTokenHandler_InvalidFields(t *testing.T) {
	config := &oauth1.Config{}
	handler := TokenHandler(config, testutils.AssertSuccessNotCalled(t), nil)
	ts := httptest.NewServer(ctxh.NewHandler(handler))

	// asert errors occur for different missing POST fields
	resp, err := http.PostForm(ts.URL, url.Values{"wrongFieldName": {testDigitsToken}, accessTokenSecretField: {testDigitsSecret}})
	assert.Nil(t, err)
	testutils.AssertBodyString(t, resp.Body, ErrMissingToken.Error()+"\n")

	resp, err = http.PostForm(ts.URL, url.Values{accessTokenField: {testDigitsToken}, "wrongFieldName": {testDigitsSecret}})
	assert.Nil(t, err)
	testutils.AssertBodyString(t, resp.Body, ErrMissingTokenSecret.Error()+"\n")
}

示例#12
文件: restcomm-api.go 项目: dataart-telco/apps-demo

func (api RestcommApi) MakeCall(from string, to string, callback string, statusCallback string) (*CallInfo, error) {
	Trace.Println("\tapi.MakeCall: from =", from, " to =", to, " callback =", callback)
	acc := api.User + ":" + api.Pass
	path := fmt.Sprintf("http://%[email protected]%s/restcomm/2012-04-24/Accounts/%s/Calls.json", acc, api.Server, api.User)
	resp, err := http.PostForm(path,
		url.Values{
			"From":           {from},
			"To":             {to},
			"Url":            {callback},
			"StatusCallback": {statusCallback}})

	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return nil, errors.New("Resp code is not 200 for " + path + "; StatusCode = " + strconv.Itoa(resp.StatusCode))
	}

	defer resp.Body.Close()

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

	var call CallInfo
	json.Unmarshal(body, &call)

	return &call, nil
}

示例#13
文件: notifiers.go 项目: alexrockt/noti

func slackNotify() {
	accessToken := os.Getenv(slackEnv)
	if accessToken == "" {
		log.Fatalf("Missing access token, %s must be set", slackEnv)
	}

	vals := make(url.Values)
	vals.Set("token", accessToken)
	vals.Set("text", fmt.Sprintf("%s\n%s", *title, *message))
	vals.Set("username", "noti")

	if ch := os.Getenv(slackChannelEnv); ch == "" {
		vals.Set("channel", "#random")
	} else {
		vals.Set("channel", ch)
	}

	resp, err := http.PostForm("https://slack.com/api/chat.postMessage", vals)
	if err != nil {
		log.Fatal(err)
	}

	r := make(map[string]interface{})
	if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
		resp.Body.Close()
		log.Fatal(err)
	}
	resp.Body.Close()

	if r["ok"] == false {
		log.Fatal("Slack API error: ", r["error"])
	}
}

示例#14
文件: dnspodd.go 项目: caiguanhao/dnspodd

func getListOfDomains() (*DomainList, error) {
	data := url.Values{
		"login_email":    {DNSPOD_EMAIL},
		"login_password": {DNSPOD_PASSWORD},
		"format":         {"json"},
	}
	resp, err := http.PostForm("https://dnsapi.cn/Domain.List", data)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	list := DomainList{}
	err = json.Unmarshal(body, &list)
	if err != nil {
		return nil, err
	}
	if list.Status.Code != "1" {
		return nil, errors.New(list.Status.Message)
	}
	return &list, nil
}

示例#15
文件: dnspodd.go 项目: caiguanhao/dnspodd

func getDomainRecordInfoById(id int) (*RecordList, error) {
	data := url.Values{
		"login_email":    {DNSPOD_EMAIL},
		"login_password": {DNSPOD_PASSWORD},
		"format":         {"json"},
		"domain_id":      {fmt.Sprintf("%d", id)},
	}
	resp, err := http.PostForm("https://dnsapi.cn/Record.List", data)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	list := RecordList{}
	err = json.Unmarshal(body, &list)
	if err != nil {
		return nil, err
	}
	if list.Status.Code != "1" {
		return nil, errors.New(list.Status.Message)
	}
	return &list, nil
}

示例#16
文件: stopforumspam.go 项目: naokij/GoStopForumSpam

func (c *Client) Add(spamData SpamData) (err error) {
	if spamData.Email == "" || spamData.Ip == "" || spamData.Username == "" || spamData.Evidence == "" {
		return errors.New("stopforumspam.Add error: spamData not complete")
	}
	postValues := url.Values{}
	postValues.Add("ip_addr", spamData.Ip)
	postValues.Add("email", spamData.Email)
	postValues.Add("username", spamData.Username)
	postValues.Add("evidence", spamData.Evidence)
	postValues.Add("api_key", c.apiKey)
	var resp *http.Response
	resp, err = http.PostForm(ADD_ENDPOINT, postValues)
	if err != nil {
		return err
	}
	var body []byte
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		err = fmt.Errorf("stopforumspam.Add error: %d %s", resp.StatusCode, body)
		return err
	}
	return nil
}

示例#17
文件: client.go 项目: elct9620/go-plurk-robot

// Send POST Request to PlurkClient API
func (plurk *PlurkClient) Post(endpoint string, params url.Values) ([]byte, error) {
	requestUri := fmt.Sprintf("%s/%s", plurk.ApiBase, endpoint)
	uri, err := url.Parse(requestUri)
	// TODO(elct9620): Imrpove error handle
	if err != nil {
		return nil, err
	}
	params = signParams(&plurk.credential, "POST", uri, params)
	res, err := http.PostForm(requestUri, params)
	logger.Info("POST %s", uri.String())
	logger.Debug("Params %s", params.Encode())
	if err != nil {
		return nil, err
	}

	defer res.Body.Close()
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	if res.StatusCode != 200 {
		var responseError Error
		json.Unmarshal(data, &responseError)
		logger.Error(responseError.ErrorText)
		return nil, errors.New(responseError.ErrorText)
	}

	return data, nil
}

示例#18
文件: treasures.go 项目: emgfc/treasure_bot

func (c *Client) post(params url.Values) (resp string, err error) {
	params.Set("sessionid", strconv.Itoa(c.sessionId))
	params.Set("network", "vkontakte")
	params.Set("doublePointsBeforeLetter", "1")

	url := fmt.Sprintf(
		"https://www111.orangeapps.ru/gems/gems/site/service/service.php?api_url=https://api.vk.com/api.php&sid=&access_token=&api_id=3882511&api_settings=2097159&viewer_id=%s&viewer_type=2&secret=0ce7b1e40f&user_id=%s&group_id=0&is_app_user=1&auth_key=%s&language=0&parent_language=0&ad_info=ElsdCQdcQlxlBQdbAwJSXHt6C0Q8HTJXUVBBJRVBNwoIFjI2HA8E&is_secure=1&ads_app_id=3882511_ea21030310f4b19893&referrer=user_apps&lc_name=cc6596bb&hash=",
		c.id,
		c.id,
		c.auth,
	)

	r, err := http.PostForm(url, params)
	if err != nil {
		return
	}
	defer r.Body.Close()

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return
	}

	resp = string(body)

	return
}

示例#19
文件: BasicDataParser.go 项目: solring/TWCompanyTree

func main() {
	target := "http://mops.twse.com.tw/mops/web/ajax_quickpgm"
	otcForm := url.Values{
		"encodeURIComponent": {"1"},
		"firstin":            {"true"},
		"step":               {"4"},
		"checkbtn":           {"1"},
		"queryName":          {"co_id"},
		//"TYPEK2" : {"sii"},
		//"TYPEK2" : {"otc"},
		//"TYPEK2" : {"rotc"},
		"TYPEK2":   {"pub"},
		"code1":    {""},
		"keyword4": {""}}

	println("=== Data Parser for Taiwan Listed Companise ===")
	println("start parsing...")
	res, err := http.PostForm(target, otcForm)

	if err != nil {
		println(err)
		return
	}

	println(res.Status)
	//fmt.Print(res.Header)
	//basicParse(res.Body, "BasicInfo_sii.json")
	//basicParse(res.Body, "BasicInfo_otc.json")
	//basicParse(res.Body, "BasicInfo_rotc.json")
	basicParse(res.Body, "BasicInfo_pub.json")
}

示例#20
文件: main.go 项目: RaymondChou/OTTStaticServer

func checkToken(access_token string) bool {
	v := make(url.Values)
	v.Set("access_token", access_token)

	if res, err := http.PostForm(OTTServerVerifyTokenAPI, v); err == nil {
		result, err := ioutil.ReadAll(res.Body)
		res.Body.Close()
		if err != nil {
			fmt.Printf("%v", err)
			return false
		}

		var resultT ResultT

		err = json.Unmarshal(result, &resultT)
		if err != nil {
			fmt.Printf("%v", err)
			return false
		}

		if resultT.Ret != 0 {
			return false
		} else {
			return true
		}

	} else {
		fmt.Printf("%v", err)
		return false
	}

}

示例#21
文件: transaction.go 项目: xbee/factom-cli

func postCmd(cmd string) {
	resp, err := http.PostForm(cmd, nil)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	resp.Body.Close()

	b := new(Response)
	if err := json.Unmarshal(body, b); err != nil {
		fmt.Printf("Failed to parse the response from factomd: %s\n", body)
		os.Exit(1)
	}

	fmt.Println(b.Response)

	if !b.Success {
		os.Exit(1)
	}

	return
}

示例#22
文件: payload.go 项目: gistia/slackbot

// Send uses the IncomingWebhook API to post a message to a slack channel
func (i *IncomingWebhook) Send() error {
	u := os.Getenv(fmt.Sprintf("%s_IN_URL", strings.ToUpper(i.Domain)))
	if u == "" {
		return fmt.Errorf("Slack incoming webhook url not found for domain %s (check %s)", i.Domain, fmt.Sprintf("%s_IN_URL", strings.ToUpper(i.Domain)))
	}
	webhook, err := url.Parse(u)
	if err != nil {
		log.Printf("Error parsing incoming webhook URL: %v", err)
		return err
	}

	p, err := json.Marshal(i)
	if err != nil {
		return err
	}

	log.Printf("Payload: %s", string(p))

	data := url.Values{}
	data.Set("payload", string(p))

	webhook.RawQuery = data.Encode()
	resp, err := http.PostForm(webhook.String(), data)
	if resp.StatusCode != 200 {
		message := fmt.Sprintf("ERROR: Non-200 Response from Slack Incoming Webhook API: %s", resp.Status)
		log.Println(message)
	}
	return err
}

示例#23
文件: simsimi.go 项目: BownX/tiebarobot

func Talk(message string) string {
	resp, err := http.PostForm(SIMSIMI_API,
		url.Values{
			"req":  {message},
			"uid":  {"36140266"},
			"lc":   {"ch"},
			"tz":   {"Asia%2FShanghai"},
			"ft":   {"0"},
			"os":   {"a"},
			"av":   {"1.0"},
			"vkey": {"30cfbb7a6d3b49029caa3c7679865860"},
			"type": {"tta"}})
	if err != nil {
		return "Error When Talking To Simsimi !"
	}
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "Error Analyzing Simsimi's Reply"
	}
	simResp := new(SimResp)
	json.Unmarshal(content, simResp)
	return simResp.Sentence_resp
}

示例#24
文件: response.go 项目: mattn/go-facebook

func PostForm(requestUrl string, data map[string]string) (r *Response, err error) {
	var postData url.Values
	for k, v := range data {
		postData[k] = []string{v}
	}
	resp, err := http.PostForm(requestUrl, postData)
	if resp != nil {
		defer resp.Body.Close()
	}
	if err != nil {
		return nil, errors.New("Post(" + requestUrl + "): " + err.Error())
	}
	if loc, err := resp.Location(); err == nil {
		r = &Response{Url: requestUrl, FinalUrl: loc.String()}
	} else {
		r = &Response{Url: requestUrl, FinalUrl: requestUrl}
	}
	r.Data, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	// Check for error
	var value FBError
	err = json.Unmarshal(r.Data, &value)
	if err == nil {
		if value.Err != nil {
			err = errors.New(value.Err.Type + ": " + value.Err.Message)
			return
		}
	}
	return r, nil // Dont return the check of an Error error
}

示例#25
文件: browserid.go 项目: PatrickHeneise/sync_gateway

// Verifies a BrowserID/Persona assertion received from a client, returning either the verification
// response (which includes the verified email address) or an error.
// The 'audience' parameter must be the same as the 'origin' parameter the client used when
// requesting the assertion, i.e. the root URL of this website.
func VerifyBrowserID(assertion string, audience string) (*BrowserIDResponse, error) {
	// See <https://developer.mozilla.org/en-US/docs/Persona/Remote_Verification_API>
	res, err := http.PostForm("https://verifier.login.persona.org/verify",
		url.Values{"assertion": {assertion}, "audience": {audience}})
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if res.StatusCode >= 300 {
		return nil, &base.HTTPError{http.StatusBadGateway,
			fmt.Sprintf("BrowserID verification server status %d", res.Status)}
	}
	responseBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, &base.HTTPError{http.StatusBadGateway, "Invalid response from BrowserID verifier"}
	}
	var response BrowserIDResponse
	if err = json.Unmarshal(responseBody, &response); err != nil {
		return nil, &base.HTTPError{http.StatusBadGateway, "Invalid response from BrowserID verifier"}
	}
	if response.Status != "okay" {
		return nil, &base.HTTPError{http.StatusUnauthorized, response.Reason}
	}
	return &response, nil
}

示例#26
文件: credentials.go 项目: esdee-git/deligo

func (c *Credentials) Authenticate() error {
	values := url.Values{}
	values.Set("client_id", c.ClientId)
	values.Set("client_secret", c.ClientSecret)
	values.Set("grant_type", "credentials")
	values.Set("username", c.Username)
	values.Set("password", c.Password)

	resp, err := http.PostForm(auth_url, values)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 {
		msg := fmt.Sprintf("Auth failed. Response %s.", resp.Status)
		return errors.New(msg)
	}

	defer resp.Body.Close()

	auth_response := new(authResponse)

	err = json.NewDecoder(resp.Body).Decode(&auth_response)
	if err != nil {
		return err
	}

	c.AccessToken = auth_response.Access_token
	c.Status = auth_response.Status

	return nil
}

示例#27
文件: adaptor.go 项目: hybridgroup/gobot

// request makes request to Particle cloud server, return err != nil if there is
// any issue with the request.
func (s *Adaptor) request(method string, url string, params url.Values) (m map[string]interface{}, err error) {
	var resp *http.Response

	if method == "POST" {
		resp, err = http.PostForm(url, params)
	} else if method == "GET" {
		resp, err = http.Get(url)
	}

	if err != nil {
		return
	}

	buf, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return
	}

	json.Unmarshal(buf, &m)

	if resp.Status != "200 OK" {
		err = fmt.Errorf("%v: error communicating to the Particle cloud", resp.Status)
	} else if _, ok := m["error"]; ok {
		err = errors.New(m["error"].(string))
	}

	return
}

示例#28
文件: connect.go 项目: alexandre-normand/slack

// Authenticate with Slack to retrieve websocket connection URL.
func handshake(apiUrl string, token string) (*Config, error) {
	resp, err := http.PostForm(apiUrl, url.Values{"token": {token}})

	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return nil, err
	}

	var data Config
	err = json.Unmarshal(body, &data)
	if err != nil {
		log.Printf("%T\n%s\n%#v\n", err, err, err)
		switch v := err.(type) {
		case *json.SyntaxError:
			log.Println(string(body[v.Offset-40 : v.Offset]))
		}
		log.Printf("%s", body)
		return nil, err
	}

	return &data, nil
}

示例#29
文件: client.go 项目: dysolution/sleepwalker

// getToken submits the provided credentials to the OAuth2 endpoint and
// returns a token that can be used to authenticate HTTP requests to the API.
func getToken(credentials *Credentials, oAuthEndpoint string) Token {
	desc := "getToken"
	if credentials.areInvalid() {
		Log.Fatal("Not all required credentials were supplied.")
	}

	uri := oAuthEndpoint
	Log.WithFields(map[string]interface{}{
		"path": uri,
	}).Debug(desc)

	values := formValues(credentials)
	Log.WithFields(map[string]interface{}{
		"values": values.Encode(),
	}).Debug(desc)

	resp, err := http.PostForm(uri, values)
	if err != nil {
		Log.Fatal(err)
	}
	defer resp.Body.Close()

	payload, err := ioutil.ReadAll(resp.Body)
	Log.WithFields(map[string]interface{}{
		"status":           resp.Status,
		"response_payload": string(payload),
	}).Debug(desc)
	return tokenFrom(payload)
}

示例#30
文件: ape.go 项目: shogo82148/ape-slack

func (con *Connection) newWSConnection() (*websocket.Conn, error) {
	resp, err := http.PostForm("https://slack.com/api/rtm.start", url.Values{"token": {con.token}})
	if err != nil {
		return nil, err
	}

	var r struct {
		Ok    bool   `json:"ok"`
		Url   string `json:"url"`
		Error string `json:"error"`
		Self  struct {
			Id   string `json:"id"`
			Name string `json:"name"`
		} `json:"self"`
		Users []struct {
			Id   string `json:"id"`
			Name string `json:"name"`
		} `json:"users"`
	}

	err = json.NewDecoder(resp.Body).Decode(&r)
	if err != nil {
		return nil, err
	}

	con.userId = r.Self.Id
	con.userName = r.Self.Name
	userMap := map[string]string{}
	for _, user := range r.Users {
		userMap[user.Id] = user.Name
	}
	con.userMap = userMap

	return websocket.Dial(r.Url, "", "https://slack.com/")
}

展开阅读全文