golang带cookie post get请求 例子

golang带cookie post get请求 例子

// test project main.go
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

type Jar struct {
    cookies []*http.Cookie
}

func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    jar.cookies = cookies
}
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
    return jar.cookies
}

func main() {
    //  response, err := http.PostForm("http://127.0.0.1:8080/admin/user/login", map[string][]string{"username": []string{"admin"}, "pass": []string{"admin"}})

    jar := new(Jar)

    client := &http.Client{nil, nil, jar, 99999999999992}

    //req, _ := http.NewRequest("POST", "http://127.0.0.1:8080/admin/user/login", nil)

    resp, err := client.PostForm("http://127.0.0.1:8080/admin/user/login", map[string][]string{"username": {"admin"}, "pass": {"admin"}})

    if err != nil {
        panic(err.Error())
    }

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

    resp, err = client.Get("http://127.0.0.1:8080/admin/column/list")

    if err != nil {
        panic(err.Error())
    }

    body, err = ioutil.ReadAll(resp.Body)

    fmt.Println(string(body))

    cookies := resp.Cookies()

    fmt.Println("xxxx")
    for _, cookie := range cookies {
        fmt.Println("cookie:", cookie.Name)
    }
}

原文地址

你可能感兴趣的:(golang带cookie post get请求 例子)