Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go标准库net/http包

Go标准库net/http包的实现

作者:我叫黑大帅

net/http是Go官方自带的 HTTP 框架,不用装任何第三方库,本文就来详细的介绍一下Go标准库net/http包的实现,感兴趣的可以了解一下

net/http 是 Go 官方自带的 HTTP 框架,不用装任何第三方库,直接就能写:

服务端

核心 API

package main

import (
	"fmt"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	// r.Method 可以判断是 GET 还是 POST
	fmt.Fprintf(w, "你好,你访问的路径是: %s", r.URL.Path)
}

func main() {
	// 1. 路由注册
	http.HandleFunc("/", helloHandler)

	// 2. 启动服务,监听 8080 端口
	fmt.Println("服务器启动在 http://localhost:8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}

HandleFunc与接口函数

// `net/http` 定义了一个接口
type Handler interface {
    ServeHTTP(w http.ResponseWriter, r *http.Request)
}


func(w http.ResponseWriter, r *http.Request)
w http.ResponseWriter 给客户端返回数据(写响应)
w.Write([]byte("返回内容"))
w.WriteHeader(404) // 设置状态码
fmt.Fprintln(w, "hello") // 也可以这样写
r *http.Request 获取客户端传过来的东西

常用的 5 种HandleFunc用法

处理 GET 请求(获取 URL 参数)

http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
	// 获取 ?name=xxx & age=xxx
	name := r.URL.Query().Get("name")
	age := r.URL.Query().Get("age")

	w.Write([]byte("名字:" + name + " 年龄:" + age))
})

处理 POST 表单(前端提交数据)

http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
	// 解析 POST 表单
	r.ParseForm()

	// 获取表单参数
	username := r.PostForm.Get("username")
	password := r.PostForm.Get("password")

	w.Write([]byte("用户名:" + username + " 密码:" + password))
})

返回 JSON(写 API 接口)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

http.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) {
	user := User{Name: "张三", Age: 20}

	// 设置返回格式 JSON
	w.Header().Set("Content-Type", "application/json")

	// 编码并返回
	json.NewEncoder(w).Encode(user)
})

路由分组 / 多个接口

// 首页
http.HandleFunc("/", homeHandler)

// 用户相关
http.HandleFunc("/user/list", userListHandler)
http.HandleFunc("/user/info", userInfoHandler)

// 登录
http.HandleFunc("/login", loginHandler)

访问静态文件服务

// 访问 /static/ 下的文件 
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

ServeMux 与自定义 Handler

mux := http.NewServeMux()
mux.HandleFunc("/user", userHandler)
// 将 mux 传入 ListenAndServe
http.ListenAndServe(":8080", mux)

直接使用 http.HandleFunc (默认模式)

当你直接调用 http.HandleFunc 时,Go 会在后台使用一个全局默认的实例,叫 DefaultServeMux

使用 http.NewServeMux() (自定义模式)

当你创建自己的 mux 时,你是在创建一个隔离的路由表

package main

import (
	"fmt"
	"net/http"
)

func main() {
	// --- 局部变量 1:给普通用户的路由 ---
	userMux := http.NewServeMux()
	userMux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "这是【普通用户】的个人中心")
	})

	// --- 局部变量 2:给管理员的路由 ---
	adminMux := http.NewServeMux()
	adminMux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "这是【管理员】的用户管理界面")
	})

	// 在 8080 端口启动用户服务
	go http.ListenAndServe(":8080", userMux)

	// 在 9090 端口启动管理服务
	fmt.Println("服务已启动:8080 为用户,9090 为管理")
	http.ListenAndServe(":9090", adminMux)
}

客户端

常用 API

resp, err := http.Get("https://api.github.com")
if err != nil {
    log.Fatal(err)
}
// 记得关闭 Body,防止内存泄漏
defer resp.Body.Close()

// 读取响应内容
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))

到此这篇关于Go标准库net/http包的实现的文章就介绍到这了,更多相关Go标准库net/http包内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文