Go Web——http标准库

文章目录

  • 简介
  • 一 HTTP Client
    • 1.1 发送GET请求
    • 1.2 解析JSON类型返回结果
    • 1.3 GET请求添加请求头
    • 1.4 发送POST请求
    • 1.5 发送JSON数据的POST请求
    • 1.6 使用Client自定义请求
  • 二 HTTP Server
    • 2.1 默认的Server
    • 2.2 自定义Server


简介

Golang http标准库提供了HTTP客户端和服务端的实现。

注意了,客户端实现可以发出http请求,并解析响应。服务器可以实现http server功能。市面上的所有golang web框架都是基于http标准库实现的。

Get、Head、Post和PostForm函数发出HTTP/ HTTPS请求。

resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
	url.Values{
   "key": {
   "Value"}, "id": {
   "123"}})

程序在使用完回复后必须关闭回复的主体。

resp, err := http.Get("http://example.com/")
if err != nil {
   
	// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...

一 HTTP Client

1.1 发送GET请求

func Get(url string) (resp *Response, err error)

Get向指定的URL发出一个GET请求,如果回应的状态码如下,Get会在调用c.CheckRedirect后执行重定向:

  • 301 (Moved Permanently)
  • 302 (Found)
  • 303 (See Other)
  • 307 (Temporary Redirect)

如果c.CheckRedirect执行失败或存在HTTP协议错误时,本方法将返回该错误;如果回应的状态码不是2xx,本方法并不会返回错误。如果返回值err为nil,resp.Body总是非nil的,调用者应该在读取完resp.Body后关闭它

Get是对包变量DefaultClient的Get方法的包装。

实例演示:

package main

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

func main() {
   
	url := "http://apis.juhe.cn/simpleWeather/query?city=成都&key=904d15a2893c4d81c5c5a1fd0a7a7ed6"
	r, err := http.Get(url)
	if err != nil {
   
		log.Fatal(err)
	}
	b, err := ioutil.ReadAll(r.Body)
	r.Body.Close()	// 程序在使用完response后必须关闭回复的主体。
	if err != nil {
   
		log.Fatal(err)
	}
	fmt.Printf("b: %v\n", string(b))
}

运行结果:

[Running] go run "e:\golang开发学习\go_pro\test.go"
b: {
   "reason":"查询成功!","result":{
   "city":"成都","realtime":{
   "temperature":"39","humidity":"30","info":"多云","wid":"01","direct":"西南风","power":"3级","aqi":"78"},"future":[{
   "date":"2022-08-21","temperature":"27\/39℃","weather":"多云转阴","wid":{
   "day":"01","night":"02"},"direct":"持续无风向"},{
   "date":"2022-08-22","temperature":"27\/39℃","weather":"阴转晴","wid":{
   "day":"02","night":"00"},"direct":"持续无风向"},{
   "date":"2022-08-23","temperature":"29\/38℃","weather":"多云","wid":{
   "day":"01","night":"01"},"direct":"持续无风向"},{
   "date":"2022-08-24","temperature":"27\/37℃","weather":"多云转小雨","wid":{
   "day":"01","night":"07"},"direct":"持续无风向"},{
   "date":"2022-08-25","temperature":"23\/35℃","weather":"小雨转中雨","wid":{
   "day":"07","night":"08"},"direct":"持续无风向"}]},"error_code":0}

[Done] exited with code=0 in 1.636 seconds

还可以把一些参数做成变量而不是直接放到URL里:

package main

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

func main() {
   
	params := url.Values{
   }
	u, err := url.Parse("http://apis.juhe.cn/simpleWeather/query")
	if err != nil {
   
		log.Fatal(err)
	}
	params.Set("city", "成都")
	params.Set("key", "904d15a2893c4d81c5c5a1fd0a7a7ed6")

	// 如果参数中有中文,则堆params进行encode
	u.RawQuery = params.Encode()
	urlPath := u.

你可能感兴趣的:(Go,Web,golang,http)