net/http 01

用 net/http 包可以快速起一个 web 服务

package main
import (
"fmt"
"net/http"
)
func helloWorld(w http.ResponseWriter, req *http.Request) {
_, err := fmt.Fprintf(w, "Hello world!")
if err != nil {
fmt.Println("code: 500")
}
}
func main() {
http.HandleFunc("/hello", helloWorld)
err := http.ListenAndServe("0.0.0.0:8080", nil)
if err != nil {
fmt.Println("Listen is failed", err)
}
}
用 net/http 作为 http client 发起 get 请求
  • 不带参数的请求
func Req() {
resp, err := http.Get("https://www.cnblogs.com/")
if err != nil {
fmt.Println("Requests is failed")
}
defer resp.Body.Close() // 从 response 读取响应内容之后必须关闭
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
  • 带参数的请求需要用 net/url 包
func ReqParser() {
// base url
baseURL := "https://baijiahao.baidu.com/s"
// params
params := url.Values{}
params.Set("id", "1775182904014714278")
params.Set("wfr", "spider")
params.Set("for", "pc")
u, err := url.ParseRequestURI(baseURL) // url.ParseRequestURI 可以将原始的 url 解析为 url 结构
if err != nil {
fmt.Printf("host:%s is failed err:%s", u.Host, err)
}
u.RawQuery = params.Encode() // url 参数 encode
rawURL := u.String()
fmt.Println(rawURL) // https://baijiahao.baidu.com/s?for=pc&id=1775182904014714278&wfr=spider
resp, err := http.Get(rawURL)
defer resp.Body.Close()
fmt.Println(resp.Header) // response header
content, _ := io.ReadAll(resp.Body) // body
fmt.Println(string(content))
}
func ReqParser01() {
// https://hanyu.baidu.com/shici/detail?from=aladdin&pid=aab6b2ffc6a64abb8c7afb5ad1bad000
endpoint := "https://hanyu.baidu.com/shici/detail"
client := &http.Client{Timeout: time.Second * 3} // 自定义 http client, 并设置超时时间
req, _ := http.NewRequest(http.MethodGet, endpoint, nil) // 创建 request 对象
params := url.Values{}
params.Add("from", "aladdin")
params.Add("pid", "aab6b2ffc6a64abb8c7afb5ad1bad000")
req.URL.RawQuery = params.Encode()
req.Header.Add("User-Agent", "xxx-uuu") // 自定义 UA
resp, _ := client.Do(req)
defer resp.Body.Close()
byte, _ := io.ReadAll(resp.Body)
fmt.Println(string(byte))
}
用 net/http 作为 http client 发起 post 请求
func reqPost() {
url := "http://172.22.143.197:8080/recv"
data := `{"name": "siri", "address": "HK"}`
// strings.NewReader 将一个字符串转换为实现io.Reader接口的类型
resp, _ := http.Post(url, "application/json", strings.NewReader(data))
defer resp.Body.Close()
content, _ := io.ReadAll(resp.Body) // body
fmt.Println(string(content))
fmt.Println(resp.Header)
}
func reqPost01() {
endpoint := "http://172.22.143.197:8080/recv"
data := struct {
name string
age int
}{
name: "siri",
age: 16,
}
payload, _ := json.Marshal(data)
// bytes.NewReader 将一个 byte 类型转换为实现 io.Reader 接口的类型
http.Post(endpoint, "application/json", bytes.NewReader(payload))
}
服务端接收 request.data
func Receiver(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
byte, err := io.ReadAll(req.Body)
if err != nil {
fmt.Printf("request data is failed!, err:%s", err)
return
}
fmt.Println(string(byte))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
return
}
func main() {
http.HandleFunc("/recv", Receiver)
err := http.ListenAndServe("0.0.0.0:8080", nil)
if err != nil {
fmt.Println("Listen is failed", err)
}
}
posted @   梦里花。  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示