发送Get请求
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "http://apis.juhe.cn/simpleWeather/query?key=087d7d10f700d20e27bb753cd806e40b&city=北京"
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("b: %v\n", string(b))
}
GET请求,将参数做成变量
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
param := url.Values{}
url, err := url.Parse("http://apis.juhe.cn/simpleWeather/query")
if err != nil {
return
}
param.Set("key", "087d7d10f700d20e27bb753cd806e40b")
param.Set("city", "北京")
url.RawQuery = param.Encode()
urlPath := url.String()
fmt.Println(urlPath)
resp, err := http.Get(urlPath)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
解析JSON类型返回结果
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
type result struct {
Args string `json:"args"`
Headers map[string]string `json:"headers"`
Origin string `json:"origin"`
Url string `json:"url"`
}
resp, err := http.Get("http://httpbin.org/get")
if err != nil {
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
var res result
_ = json.Unmarshal(body, &res)
fmt.Printf("%#v", res)
}
GET请求添加请求头
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
client := http.Client{}
req, _ := http.NewRequest("GET", "http://httpbin.org/get", nil)
req.Header.Add("name", "牛牛")
req.Header.Add("age", "18")
resp, _ := client.Do(req)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf(string(body))
}
发送POST请求
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
path := "http://apis.juhe.cn/simpleWeather/query"
urlValues := url.Values{}
urlValues.Add("key", "087d7d10f700d20e27bb753cd806e40b")
urlValues.Add("city", "北京")
r, err := http.PostForm(path, urlValues)
if err != nil {
log.Fatal(err)
}
defer r.Body.Close()
b, _ := ioutil.ReadAll(r.Body)
fmt.Printf("b: %v\n", string(b))
}
另一种方式
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func main() {
urlValues := url.Values{
"name": {"牛牛"},
"age": {"18"},
}
reqBody := urlValues.Encode()
resp, _ := http.Post("http://httpbin.org/post", "text/html", strings.NewReader(reqBody))
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
JSON格式的POST请求
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
data := make(map[string]interface{})
data["site"] = "www.duoke360.com"
data["name"] = "多课网"
bytesData, _ := json.Marshal(data)
resp, _ := http.Post("http://httpbin.org/post", "application/json", bytes.NewReader(bytesData))
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
使用Client自定义请求
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
client := http.Client{
Timeout: time.Second * 5,
}
url := "http://apis.juhe.cn/simpleWeather/query?key=087d7d10f700d20e27bb753cd806e40b&city=北京"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Add("referer", "http://apis.juhe.cn/")
res, err2 := client.Do(req)
if err2 != nil {
log.Fatal(err2)
}
defer res.Body.Close()
b, _ := ioutil.ReadAll(res.Body)
fmt.Printf("b: %v\n", string(b))
}
HTTP Server
package main
import (
"io"
"log"
"net/http"
)
func main() {
f := func(resp http.ResponseWriter, req *http.Request) {
io.WriteString(resp, "hello world")
}
http.HandleFunc("/hello", f)
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal(err)
}
}
使用Handler实现并发处理
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
type countHandler struct {
mu sync.Mutex
n int
}
func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
h.n++
fmt.Fprintf(w, "count is %d\n", h.n)
}
func main() {
http.Handle("/count", new(countHandler))
log.Fatal(http.ListenAndServe(":8080", nil))
}