func main() { flag.Parse() if flag.NArg() < 1 { fmt.Fprintf(os.Stderr, "Usage: %s [URL]\n", os.Args[0]) os.Exit(1) } u := "http://kon.tl/create.php" d := map[string]string{"url": flag.Arg(0)} fmt.Println(" Long URL:", flag.Arg(0)) r, err := http.PostForm(u, d) if err != nil { log.Fatalln(err) } defer r.Body.Close() b, err := ioutil.ReadAll(r.Body) if err != nil { log.Fatalln(err) } s := string(b) x := regexp.MustCompile("<a href=(.*) target=_blank>") m := x.FindStringSubmatch(s)[1] fmt.Println("Short URL:", m) }
func (c *Client) request(credentials *Credentials, url string, param web.ParamMap) (*Credentials, web.ParamMap, os.Error) { c.SignParam(credentials, "POST", url, param) resp, err := http.PostForm(url, param.StringMap()) 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.ParamMap) 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 }
func verifyAssertion(params map[string]string) bool { fields := map[string]string{"openid.mode": "check_authentication"} for k, v := range params { if k != "openid.mode" { fields[k] = v } } resp, err := http.PostForm(params["openid.op_endpoint"], fields) if err != nil { log.Println(err.String()) return false } defer resp.Body.Close() content, err := ioutil.ReadAll(resp.Body) response := string(content) log.Println(response) lines := strings.Split(response, "\n", -1) for _, l := range lines { if l == "is_valid:true" { return true } } return false }
func processStats() { for { sr, ok := <-statReportChannel if !ok { done <- true break } if Verbose { log.Printf("posting stat to stathat: %s, %v", sr.url(), sr.values()) } if testingEnv { testPostChannel <- &testPost{sr.url(), sr.values()} continue } r, err := http.PostForm(sr.url(), sr.values()) if err != nil { log.Printf("error posting stat to stathat: %s", err) continue } if Verbose { body, _ := ioutil.ReadAll(r.Body) log.Printf("stathat post result: %s", body) } r.Body.Close() } }
func PostFacebookLink(text string, urls []string) { u := make(url.Values) u.Add("access_token", accessToken) u.Add("link", url.QueryEscape(urls[0])) u.Add("message", url.QueryEscape(text)) http.PostForm(linkURL, u) }
func bye(ctx *web.Context) { res, err := http.PostForm("http://fantasyherald.com/quiz/dand/index.php", ctx.Request.Params) if err == nil { io.Copy(ctx, res.Body) defer res.Body.Close() } return }
func post() { url := fmt.Sprintf("http://%s/add", hosts[rand.Intn(len(hosts))]) r, err := http.PostForm(url, map[string]string{"url": fooUrl}) if err != nil { log.Println("post:", err) return } defer r.Body.Close() b, err := ioutil.ReadAll(r.Body) if err != nil { log.Println("post:", err) return } newURL <- string(b) stat.In <- "put" }
func updateTokens(params map[string][]string) (err os.Error) { println("Call: " + TOKENS_ENDPOINT) response, _ := http.PostForm(TOKENS_ENDPOINT, params) b, _ := ioutil.ReadAll(response.Body) println(string(b)) var responseJson map[string]interface{} json.Unmarshal(b, &responseJson) if errorMessage, ok := responseJson["error"]; ok { return os.ErrorString(errorMessage.(string)) } else { currentTokens = &tokens{responseJson["access_token"].(string), responseJson["refresh_token"].(string)} currentTokens.store() return nil } return os.ErrorString("access_token is null") }
func postTweet(token *oauth.Credentials, url string, opt map[string]string) os.Error { param := make(web.Values) for k, v := range opt { param.Set(k, v) } oauthClient.SignParam(token, "POST", url, param) res, err := http.PostForm(url, http.Values(param)) if err != nil { log.Println("failed to post tweet:", err) return err } defer res.Body.Close() if res.StatusCode != 200 { log.Println("failed to get timeline:", err) return err } return nil }
// Login to the minecraft.net website using HTTPS. func (c *minecraftClient) Login(username, password string) (err os.Error) { param := make(web.ParamMap) param.Set("username", username) param.Set("password", password) param.Set("use_secure", "true") url := MINECRAFT_LOGIN_URL + "?" + param.FormEncodedString() var resp *http.Response done := make(chan bool, 1) go func() { resp, err = http.PostForm(url, param.StringMap()) done <- true }() timeout := time.After(MINECRAFT_NET_TIMEOUT * 1e9) // select { case <-done: break case <-timeout: return os.NewError("Login attempt timed out - " + MINECRAFT_LOGIN_URL) } if resp == nil { return os.NewError("Login server responded with a null body.") } switch resp.StatusCode { // A successful minecraft.net login is followed by a 302. case 302: if r, ok := resp.Header["Location"]; ok && len(r) > 0 { if r[0] == "https://www.minecraft.net/" { log.Println("Login successful.") return nil } else { return os.NewError("Login redirecting to unknown page: " + r[0]) } } case 200: return os.NewError("Login failed.") } return os.NewError("Login return code: " + string(resp.StatusCode)) }
// authLogin return auth code from AuthSub server. // see: http://code.google.com/apis/accounts/docs/AuthForWebApps.html func authLogin(config map[string]string) (auth string) { res, err := http.PostForm( "https://www.google.com/accounts/ClientLogin", map[string]string{ "accountType": "GOOGLE", "Email": config["email"], "Passwd": config["password"], "service": "code", "source": "golang-goissue-" + version, }) if err != nil { log.Fatal("failed to authenticate:", err) } defer res.Body.Close() b, _ := ioutil.ReadAll(res.Body) if res.StatusCode != 200 { log.Fatal("failed to authenticate:", res.Status) } lines := strings.Split(string(b), "\n", -1) return lines[2] }
func pingUser(twitterId int64, pingUrl string) { fmt.Printf("Pinging for update by user %d...\n", twitterId) resp, postErr := http.PostForm( pingUrl, url.Values{ "update_twitter_id": {fmt.Sprintf("%d", twitterId)}, "secret": {*streamSpigotSecret}, }) if postErr != nil { fmt.Printf(" ...got error %s when trying to POST ping\n", postErr) return } defer resp.Body.Close() if resp.StatusCode != 200 { fmt.Printf(" ...got HTTP status %d when trying to POST ping\n", resp.StatusCode) return } fmt.Printf(" ...success\n") }
// Data in param must be URL escaped already. func (tw *twitterClient) twitterPost(url string, param web.ParamMap) (p []byte, err os.Error) { oauthClient.SignParam(tw.twitterToken, "POST", url, param) // TODO: remove this dupe. var resp *http.Response done := make(chan bool, 1) go func() { resp, err = http.PostForm(url, param.StringMap()) done <- true }() timeout := time.After(TWITTER_GET_TIMEOUT * 1e9) // post in this case. select { case <-done: break case <-timeout: return nil, os.NewError("http POST timed out - " + url) } if resp == nil { panic("oops") } return readHttpResponse(resp, err) }
// dash runs the given method and command on the dashboard. // If args is not nil, it is the query or post parameters. // If resp is not nil, dash unmarshals the body as JSON into resp. func dash(meth, cmd string, resp interface{}, args param) os.Error { var r *http.Response var err os.Error if *verbose { log.Println("dash", cmd, args) } cmd = "http://" + *dashboard + "/" + cmd vals := make(url.Values) for k, v := range args { vals.Add(k, v) } switch meth { case "GET": if q := vals.Encode(); q != "" { cmd += "?" + q } r, err = http.Get(cmd) case "POST": r, err = http.PostForm(cmd, vals) default: return fmt.Errorf("unknown method %q", meth) } if err != nil { return err } defer r.Body.Close() var buf bytes.Buffer buf.ReadFrom(r.Body) if resp != nil { if err = json.Unmarshal(buf.Bytes(), resp); err != nil { log.Printf("json unmarshal %#q: %s\n", buf.Bytes(), err) return err } } return nil }
// dash runs the given method and command on the dashboard. // If args is not nil, it is the query or post parameters. // If resp is not nil, dash unmarshals the body as JSON into resp. func dash(meth, cmd string, resp interface{}, args param) os.Error { var r *http.Response var err os.Error if *verbose { log.Println("dash", cmd, args) } cmd = "http://" + *dashboard + "/" + cmd switch meth { case "GET": if args != nil { m := make(map[string][]string) for k, v := range args { m[k] = []string{v} } cmd += "?" + http.EncodeQuery(m) } r, err = http.Get(cmd) case "POST": r, err = http.PostForm(cmd, args) default: return fmt.Errorf("unknown method %q", meth) } if err != nil { return err } defer r.Body.Close() var buf bytes.Buffer buf.ReadFrom(r.Body) if resp != nil { if err = json.Unmarshal(buf.Bytes(), resp); err != nil { log.Printf("json unmarshal %#q: %s\n", buf.Bytes(), err) return err } } return nil }
func SmushFiles(response http.ResponseWriter, request *http.Request) { var requiredParams = []string{"name", "source"} if request.Method != "POST" { http.Error(response, "Must post from main Smush form", http.StatusInternalServerError) return } if !RequireParams(request, requiredParams) { http.Error(response, "Missing required params", http.StatusInternalServerError) return } var source []string source = request.Form["source"] sourceStrings := make([]string, len(source)) i := 0 // move the source urls into a new array so we can preserve the order, but skip blank entries for _, v := range source { if v != "" { sourceStrings[i] = v i++ } } compileParamString := "compilation_level=SIMPLE_OPTIMIZATIONS" compileParamString += "&output_format=text" compileParamString += "&output_info=compiled_code" for _, v := range sourceStrings[:i] { compileParamString += "&code_url=" + v } compileParams, _ := url.ParseQuery(compileParamString) compileResponse, _ := http.PostForm(compilerURL, compileParams) result, _ := ReadWholeFile(compileResponse.Body) if len(result) == 1 { http.Error(response, "Something went wrong with the Closure Compiler", http.StatusInternalServerError) return } currentTime := time.LocalTime().Nanoseconds() dirName := "out/" + strconv.Itoa64(currentTime) fileName := dirName + "/" + request.Form["name"][0] + ".min.js" if err := os.Mkdir(dirName, uint32(0777)); err != nil { http.Error(response, "Couldn't create output folder", http.StatusInternalServerError) return } outputFile, err := os.Create(fileName) if err != nil { http.Error(response, "Couldn't create output file", http.StatusInternalServerError) return } _, err = outputFile.WriteString(result) if err != nil { http.Error(response, "Couldn't write output to file", http.StatusInternalServerError) return } http.Redirect(response, request, "/"+fileName, http.StatusFound) }
func PostFacebookStatus(text string) { u := make(url.Values) u.Set("access_token", accessToken) u.Set("message", url.QueryEscape(text)) http.PostForm(postURL, u) }