Skip to main content

[pkg] net/http

type Response#

type Response @ golang

http#

// func Get(url string) (resp *Response, err error)
resp, err := http.Get("http://example.com/")

func Get#

package main
import (
"fmt"
"net/http"
"os"
)
func main() {
resp, err := http.Get("https://pjchender.github.io")
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
}
// 下面四句可以簡寫成一句
// io.Copy(os.Stdout, resp.Body)
bs := make([]byte, 99999)
n, err := resp.Body.Read(bs)
fmt.Println(n)
fmt.Println(string(bs))
}

Post request#

post with form#

func RevokeToken(clientID, clientSecret string, token *oauth2.Token) error {
formData := url.Values{
"token": {token.AccessToken},
"token_type_hint": {"access_token"},
}
payload := strings.NewReader(formData.Encode())
client := &http.Client{}
req, err := http.NewRequest(http.MethodPost, <url>, payload)
if err != nil {
return fmt.Errorf("[pkg/pcc] http.NewRequest failed: %v", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("client.Do failed: %v", err)
}
defer res.Body.Close()
if code := res.StatusCode; code < 200 || code > 299 {
return fmt.Errorf("http.PostForm failed: %v", err)
}
return nil
}
Last updated on