学习Go语言基础类语法_Day07 net/http

1、get请求

1.1、基本实例1:

package main

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

func testGet() {
	//https://www.juhe.cn/box/index/id/73 天气查询api
    url := "http://apis.juhe.cn/simpleWeather/query?key=087d7d10f700d20e27bb753cd806e40b&city=北京"
	r, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	fmt.Printf("b: %v\n", string(b))
}
func main() {
	testGet()
}

运行结果

b: {"reason":"查询成功!","result":{"city":"北京","realtime":{"temperature":"20","humidity":"63","info":"晴","wid":"00","direct":"北风","power":"2级","aqi":"84"},"future":[{"date":"2022-09-26","temperature":"15\/28℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-27","temperature":"17\/29℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-28","temperature":"18\/29℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风转西南风"},{"date":"2022-09-29","temperature":"18\/30℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-30","temperature":"18\/30℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"}]},"error_code":0}

1.2、基本实例2:参数做成变量

GET请求,把一些参数做成变量而不是直接放到url

package main

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

func testGet2() {
	params := url.Values{}
	Url, err := url.Parse("http://apis.juhe.cn/simpleWeather/query")
	if err != nil {
		return
	}
	//设置到params中
	params.Set("key", "087d7d10f700d20e27bb753cd806e40b")
	params.Set("city", "北京")
	//如果参数中有中文参数,这个方法会进行URLEncode
	Url.RawQuery = params.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))
}

func main() {
	testGet2()
}

运行结果

http://apis.juhe.cn/simpleWeather/query?city=%E5%8C%97%E4%BA%AC&key=087d7d10f700d20e27bb753cd806e40b
{"reason":"查询成功!","result":{"city":"北京","realtime":{"temperature":"20","humidity":"63","info":"晴","wid":"00","direct":"北风","power":"2级","aqi":"84"},"future":[{"date":"2022-09-26","temperature":"15\/28℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-27","temperature":"17\/29℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-28","temperature":"18\/29℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风转西南风"},{"date":"2022-09-29","temperature":"18\/30℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-30","temperature":"18\/30℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"}]},"error_code":0}

1.3、解析JSON类型的返回结果

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"
)

func testParseJson() {
	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
    //把body解析到res中去
	_ = json.Unmarshal(body, &res)
	fmt.Printf("%#v", res)
}

运行结果

D:\GO\src\github.com\tmp>go run main.go
{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Host": "httpbin.org",
    "User-Agent": "Go-http-client/1.1",
    "X-Amzn-Trace-Id": "Root=1-6331062f-7572dae53291808504240be9"
  },
  "origin": "111.14.148.34",
  "url": "http://httpbin.org/get"
}

main.result{Args:"", Headers:map[string]string{"Accept-Encoding":"gzip", "Host":"httpbin.org", "User-Agent":"Go-http-client/1.1", "X-Amzn-Trace-Id":"Root=1-6331062f-7572dae53291808504240be9"}, Origin:"111.14.148.34", Url:"http://httpbin.org/get"}

1.4、GET请求添加请求头

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"
)

func testAddHeader() {
    //自定义一个客户端
	client := &http.Client{}
    //创建一个新的Request,get类型,url,body
	req, _ := http.NewRequest("GET", "http://httpbin.org/get", nil)
    //添加请求头
	req.Header.Add("name", "Caidd")
	req.Header.Add("age", "23")
    //使用自己定义的客户端去发这个Request
	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf(string(body))
}
func main() {
	testAddHeader()
}

运行结果

D:\GO\src\github.com\tmp>go run main.go
{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Age": "23",
    "Host": "httpbin.org",
    "Name": "Caidd",
    "User-Agent": "Go-http-client/1.1",
    "X-Amzn-Trace-Id": "Root=1-633106c7-4825dab4387c31d90be94c94"
  },
  "origin": "111.14.148.34",
  "url": "http://httpbin.org/get"
}

2、POST请求

2.1、基本实例1(常用):

package main

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

func testPost() {
	path := "http://apis.juhe.cn/simpleWeather/query"
    //定义urlValues为url.Values{}类型
	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))
}

func main() {
	testPost()
}

运行结果:

D:\GO\src\github.com\tmp>go run main.go
b: {"reason":"查询成功!","result":{"city":"济南","realtime":{"temperature":"24","humidity":"34","info":"晴","wid":"00","direct":"西风","power":"2级","aqi":"64"},"future":[{"date":"2022-09-26","temperature":"17\/28℃","weather":"晴转多云","wid":{"day":"00","night":"01"},"direct":"南风"},{"date":"2022-09-27","temperature":"19\/29℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"南风"},{"date":"2022-09-28","temperature":"19\/28℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-29","temperature":"19\/29℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"},{"date":"2022-09-30","temperature":"20\/29℃","weather":"晴转多云","wid":{"day":"00","night":"01"},"direct":"南风"}]},"error_code":0}

2.2、基本实例2:

package main

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

func testPost2() {
	urlValues := url.Values{
		"name": {"Caidd123"},
		"age":  {"23"},
	}
	reqBody := urlValues.Encode()
	resp, _ := http.Post("http://httpbin.org/post", "text/html", strings.NewReader(reqBody))
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

func main() {
	testPost2()
}

运行结果:

D:\GO\src\github.com\tmp>go run main.go
{
  "args": {},
  "data": "age=23&name=Caidd123",
  "files": {},
  "form": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Content-Length": "20",
    "Content-Type": "text/html",
    "Host": "httpbin.org",
    "User-Agent": "Go-http-client/1.1",
    "X-Amzn-Trace-Id": "Root=1-63310859-69e008d1759937d40d842262"
  },
  "json": null,
  "origin": "111.14.148.34",
  "url": "http://httpbin.org/post"
}

2.3、基本实例3-Json:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func testPostJson() {
	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))
}

func main() {
	testPostJson()
}

运行结果

D:\GO\src\github.com\tmp>go run main.go
{
  "args": {},
  "data": "{\"name\":\"\u591a\u8bfe\u7f51\",\"site\":\"www.duoke360.com\"}",
  "files": {},
  "form": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Content-Length": "46",
    "Content-Type": "application/json",
    "Host": "httpbin.org",
    "User-Agent": "Go-http-client/1.1",
    "X-Amzn-Trace-Id": "Root=1-633109d6-491c749f1d594dc33c60a2cc"
  },
  "json": {
    "name": "\u591a\u8bfe\u7f51",
    "site": "www.duoke360.com"
  },
  "origin": "111.14.148.34",
  "url": "http://httpbin.org/post"
}

3、使用Client自定义请求

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func testClient() {
	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))
}
func main() {
	testClient()
}

4、最简单的HTTP Server

使用golang实现一个http server非常简单,代码如下:

func testHttpServer() {
	// 请求处理函数
	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)
	}
}
//以后web方面基本的格式就是这样的

运行结果
访问http://127.0.0.1:9999/hello
image

5、使用Handler实现并发处理

package main

import (
	"fmt"
	"log"
	"net/http"
	"sync"
)

type countHandler struct {
	mu sync.Mutex // guards n
	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 testHttpServer2() {
	http.Handle("/count", new(countHandler))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func main() {
	testHttpServer2()
}

运行结果:
image

posted @ 2022-09-26 10:22  Caidd123  阅读(17)  评论(0)    收藏  举报