puzzle input
+12
-10
-4
-8
+18
-1
-13
...
net/html
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
检查元素cookiehttp.Get()cookieNewRequest*Request
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Cookie", "name=value")
resp, err := client.Do(req)
robots, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()//必须要关闭Body
ioutil.ReadAll()[]byte[]bytestringstring(b)unsafeunsafe
func BytesString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
[]byte*byte*stringunsafe.Pointer*byte*stringreflect.StringHeaderreflect.SliceHeaderregexpFindAllString[]stringstrconv.Atoi()
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"unsafe"
)
func BytesString(b []byte) string {//[]byte 转string
return *(*string)(unsafe.Pointer(&b))
}
func getPuzzle(url string) string {//从网页抓取数据
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Cookie", "session=53616c7xxx")
resp, err := client.Do(req)
robots, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
str := BytesString(robots)
return str
}
func sum(num []int) int {
sum := 0
for _, n := range num {
sum += n
}
return sum
}
func strtoint(str []string) []int {//string转int
num := make([]int, len(str))
for i := 0; i < len(str); i++ {
flag := str[i][0]
chafre, _ := strconv.Atoi(str[i][1:])
switch flag {
case '+':
num[i] = chafre
case '-':
num[i] = -chafre
}
}
return num
}
func main() {
change := getPuzzle("https://adventofcode.com/2018/day/1/input")
re := regexp.MustCompile("[+|-][0-9]*")//正则表达式
str := re.FindAllString(change, -1)
num := strtoint(str)
sum := sum(num)
fmt.Printf("sum is %d\n", sum)
}
如果有更好的方法,欢迎私信,哈哈哈···