分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

9.6 http中间件

发布时间:2023-09-06 01:47责任编辑:彭小芳关键词:http
package mainimport ( ???"io" ???"log" ???"net/http")type User stringfunc (u User) toString() string { ???return string(u)}type AuthHandler func(u User, w http.ResponseWriter, r *http.Request)func main() { ???// Secured API ???mux := http.NewServeMux() ???mux.HandleFunc("/api/users", Secure(func(w http.ResponseWriter, r *http.Request) { ???????io.WriteString(w, `[{"id":"1","login":"ffghi"},{"id":"2","login":"ffghj"}]`) ???})) ???mux.HandleFunc("/api/profile", WithUser(func(u User, w http.ResponseWriter, r *http.Request) { ???????log.Println(u.toString()) ???????io.WriteString(w, "{\"user\":\""+u.toString()+"\"}") ???})) ???http.ListenAndServe(":8080", mux)}func WithUser(h AuthHandler) http.HandlerFunc { ???return func(w http.ResponseWriter, r *http.Request) { ???????user := r.Header.Get("X-User") ???????if len(user) == 0 { ???????????w.WriteHeader(http.StatusUnauthorized) ???????????return ???????} ???????h(User(user), w, r) ???}}func Secure(h http.HandlerFunc) http.HandlerFunc { ???return func(w http.ResponseWriter, r *http.Request) { ???????sec := r.Header.Get("X-Auth") ???????if sec != "authenticated" { ???????????w.WriteHeader(http.StatusUnauthorized) ???????????return ???????} ???????h(w, r) // use the handler ???}}/*(sx3.5.3) ? ?~ curl -X GET -I http://127.0.0.1:8080/api/usersHTTP/1.1 401 UnauthorizedDate: Mon, 26 Mar 2018 15:42:50 GMTContent-Length: 0Content-Type: text/plain; charset=utf-8curl -X GET -w "\nStatus: %{http_code}\n" ?http://127.0.0.1:8080/api/usersStatus: 401curl -X GET -w "\nStatus: %{http_code}\n" ?http://127.0.0.1:8080/api/users ?-H "X-Auth: authenticated"[{"id":"1","login":"ffghi"},{"id":"2","login":"ffghj"}]Status: 200(sx3.5.3) ? ?~ curl -X GET -w "\nStatus: %{http_code}\n" ?http://127.0.0.1:8080/api/profile ?-H "X-User: zrd"{"user":"zrd"}Status: 200*/
在前面的例子中中间件的实现利用函数为一等公民的Golang特色。原handlerfunc包装成一个handlerfunc检查x-auth头。安全功能是用来保护handlerfunc,用于servemux的handlefunc方法。请注意,这只是一个简单的示例,但这种方式可以实现更复杂的解决方案。例如,用户的身份可以从标题标记和随后的提取,处理新类型可以定义为类AuthHandler func(U *用户,W http.responsewriter,R * HTTP请求)。功能的用户创建的servemux的handlerfunc。

9.6 http中间件

原文地址:https://www.cnblogs.com/zrdpy/p/8654939.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved