本文整理汇总了Golang中net/http.PostForm函数的典型用法代码示例。如果您正苦于以下问题:Golang PostForm函数的具体用法?Golang PostForm怎么用?Golang PostForm使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PostForm函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: crawl
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: BTestAuth
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: TestWebHandler_InvalidFields
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: postMessage
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
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: TestReport
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: RestartRouter
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: work
// 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: TestReserve
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: serveCallback
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: TestTokenHandler_InvalidFields
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: MakeCall
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: slackNotify
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: getListOfDomains
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: getDomainRecordInfoById
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
}