-
-
Save chris-ramon/0cd38ea0b418204c7d14 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"net/url" | |
"regexp" | |
"strings" | |
) | |
var loginUrl = "http://v2ex.com/signin" | |
var missionUrl = "http://v2ex.com/mission/daily" | |
var username = "your_username" | |
var password = "your_password" | |
type myCookieJar struct { | |
cookies []*http.Cookie | |
} | |
func (c *myCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) { | |
if c.cookies == nil { | |
c.cookies = make([]*http.Cookie, 0) | |
} | |
for _, it := range cookies { | |
c.cookies = append(c.cookies, it) | |
} | |
} | |
func (c *myCookieJar) Cookies(u *url.URL) []*http.Cookie { | |
return c.cookies | |
} | |
func main() { | |
cookieJar := &myCookieJar{} | |
client := http.Client{Jar: cookieJar} | |
// login | |
loginreq, _ := http.NewRequest("GET", loginUrl, nil) | |
loginresp, _ := client.Do(loginreq) | |
loginHtml, _ := ioutil.ReadAll(loginresp.Body) | |
re := regexp.MustCompile(`<input type="hidden" value="(\d+)" name="once" />`) | |
matched := re.FindStringSubmatch(string(loginHtml)) | |
params := url.Values{"next": {"/", "/"}, "u": {username}, "p": {password}, "once": {matched[1]}} | |
req, _ := http.NewRequest("POST", loginUrl, strings.NewReader(params.Encode())) | |
req.Header.Add("Host", "v2ex.com") | |
req.Header.Add("Origin", "http://v2ex.com") | |
req.Header.Add("Referer", loginUrl) | |
req.Header.Add("Content-Type", "application/x-www-form-urlencoded") | |
for _, c := range cookieJar.cookies { | |
req.AddCookie(c) | |
} | |
client.Do(req) | |
// try finish mission | |
missionReq, _ := http.NewRequest("GET", missionUrl, nil) | |
missionResp, _ := client.Do(missionReq) | |
missionHtml, _ := ioutil.ReadAll(missionResp.Body) | |
missionHtmlStr := string(missionHtml) | |
if strings.Index(missionHtmlStr, "每日登录奖励已领取") > 0 { | |
fmt.Println("每日登录奖励已领取") | |
} else { | |
re = regexp.MustCompile(`location.href = '(.*)'`) | |
matched = re.FindStringSubmatch(missionHtmlStr) | |
req, _ = http.NewRequest("GET", "http://www.v2ex.com"+matched[1], nil) | |
client.Do(req) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment