当前位置: 首页 > news >正文

北京大兴网站建设首选公司福田蒙派克柴油版7座

北京大兴网站建设首选公司,福田蒙派克柴油版7座,荣耀商城官网网站,网络服务提供商有哪些之前写的《golang实现一个BasicAuth的HTTP server》一定会做基本认证。 本例给出了如何通过启动时候指定的参数来控制是否做基本认证 代码对比和解释 给出与上一篇中源码的diff adminhpc-1:~/go/auth_http$ diff -ruN http_rpc_server.go_bak http_rpc_server.go --- http_rp…

之前写的《golang实现一个BasicAuth的HTTP server》一定会做基本认证。
本例给出了如何通过启动时候指定的参数来控制是否做基本认证

代码对比和解释

  • 给出与上一篇中源码的diff
admin@hpc-1:~/go/auth_http$ diff -ruN http_rpc_server.go_bak http_rpc_server.go
--- http_rpc_server.go_bak      2024-03-21 16:53:58.899582234 +0800
+++ http_rpc_server.go  2024-03-21 17:51:01.878115766 +0800
@@ -11,7 +11,9 @@// 定义一个用于接收请求的结构体
-type MapPrinter struct{}
+type MapPrinter struct{
+    AuthEnabled bool
+}// 定义一个用于接收请求的方法func (m *MapPrinter) PrintMap(w http.ResponseWriter, r *http.Request) {
@@ -19,23 +21,26 @@http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}
-    // 检查认证头部信息
-    username, password, ok := r.BasicAuth()
-    if !ok {
-        // 未提供基本身份验证,返回 401 Unauthorized
-        w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
-        w.WriteHeader(http.StatusUnauthorized)
-        fmt.Fprintln(w, "401 Unauthorized")
-        return
-    }
-    
-    // 验证用户名和密码
-    if !utils.CheckCredentials(username, password) {
-        // 用户名和密码不匹配,返回 401 Unauthorized
-        w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
-        w.WriteHeader(http.StatusUnauthorized)
-        fmt.Fprintln(w, "401 Unauthorized")
-        return
+    // 检查是否启用了基本认证
+    if m.AuthEnabled {
+        // 检查认证头部信息
+        username, password, ok := r.BasicAuth()
+        if !ok {
+            // 未提供基本身份验证,返回 401 Unauthorized
+            w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
+            w.WriteHeader(http.StatusUnauthorized)
+            fmt.Fprintln(w, "401 Unauthorized")
+            return
+        }
+        
+        // 验证用户名和密码
+        if !utils.CheckCredentials(username, password) {
+            // 用户名和密码不匹配,返回 401 Unauthorized
+            w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
+            w.WriteHeader(http.StatusUnauthorized)
+            fmt.Fprintln(w, "401 Unauthorized")
+            return
+        }}var payload map[string]interface{}
@@ -57,11 +62,18 @@func main() {//获取监听端口,默认8080port := flag.String("p", "8080", "指定监听端口")
+    //获取是否使能认证,默认不使能
+    authEnabled := flag.Bool("a", false, "Enable basic authentication")// 解析命令行参数flag.Parse()+    // 创建RPC服务实例
+    rpcService := &MapPrinter{
+        AuthEnabled: *authEnabled, // 根据命令行参数设置是否启用基本认证
+    }
+//注册abc-api路由
-    http.HandleFunc("/abc-api", new(MapPrinter).PrintMap)
+    http.HandleFunc("/abc-api", rpcService.PrintMap)fmt.Println("Server is listening on port %s...", *port)log.Fatal(http.ListenAndServe(":" + *port, nil))
admin@hpc-1:~/go/auth_http$ 
  • 解释
    • 定义的结构体MapPrinter增加一个bool属性AuthEnabled ,用来控制是否做基本认证
    • 之前代码中做认证的部分,只有当AuthEnabled为true的时候才执行
    • 通过flag提取-a后面跟着的true或是false用来给AuthEnabled 赋值,默认为false
    • 创建实例rpcService的时候,将flag获取的值赋给AuthEnabled
    • 注册路由的时候,直接关联到实例rpcService
  • 完整源码
admin@hpc-1:~/go/auth_http$ cat http_rpc_server.go
package mainimport ("fmt""log""flag""net/http""encoding/json""my_auth/utils"
)// 定义一个用于接收请求的结构体
type MapPrinter struct{AuthEnabled bool
}// 定义一个用于接收请求的方法
func (m *MapPrinter) PrintMap(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}// 检查是否启用了基本认证if m.AuthEnabled {// 检查认证头部信息username, password, ok := r.BasicAuth()if !ok {// 未提供基本身份验证,返回 401 Unauthorizedw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)w.WriteHeader(http.StatusUnauthorized)fmt.Fprintln(w, "401 Unauthorized")return}// 验证用户名和密码if !utils.CheckCredentials(username, password) {// 用户名和密码不匹配,返回 401 Unauthorizedw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)w.WriteHeader(http.StatusUnauthorized)fmt.Fprintln(w, "401 Unauthorized")return}}var payload map[string]interface{}err := json.NewDecoder(r.Body).Decode(&payload)if err != nil {http.Error(w, "Invalid payload", http.StatusBadRequest)return}fmt.Println("Received payload:")for key, value := range payload {fmt.Printf("%s: %v\n", key, value)}w.WriteHeader(http.StatusOK)w.Write([]byte("Map printed successfully\n"))
}func main() {//获取监听端口,默认8080port := flag.String("p", "8080", "指定监听端口")//获取是否使能认证,默认不使能authEnabled := flag.Bool("a", false, "Enable basic authentication")// 解析命令行参数flag.Parse()// 创建RPC服务实例rpcService := &MapPrinter{AuthEnabled: *authEnabled, // 根据命令行参数设置是否启用基本认证}//注册abc-api路由http.HandleFunc("/abc-api", rpcService.PrintMap)fmt.Println("Server is listening on port %s...", *port)log.Fatal(http.ListenAndServe(":" + *port, nil))
}
admin@hpc-1:~/go/auth_http$ 

验证

不使能认证

  • 运行时候不指定-a,或者 -a=false,注意,不能使用"-a false",否则一直是true!
admin@hpc-1:~/go/auth_http$ ./http_rpc_server -p 8090 -a=false
Server is listening on port %s... 8090
  • 另开终端,无论是不带basic auth header还是随便带什么basic authen header,都可以正常提供服务
admin@hpc-1:~$ curl -X POST  -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8090/abc-api
Map printed successfully
admin@hpc-1:~$ 
admin@hpc-1:~$ curl -X POST -u admin:admin -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8090/abc-api
Map printed successfully
admin@hpc-1:~$ 

使能认证

  • 运行时指定-a=true
admin@hpc-1:~/go/auth_http$ ./http_rpc_server -p 8090 -a=true
Server is listening on port %s... 8090
  • 无论是不带基础认证或者是用户名密码不匹配,都会报错
admin@hpc-1:~$ curl -X POST  -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8090/abc-api
401 Unauthorized
admin@hpc-1:~$ 
admin@hpc-1:~$ curl -X POST -u admin:nimda -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8090/abc-api
401 Unauthorized
admin@hpc-1:~$ 
  • 只有带正确的用户名密码认证的请求才会被正确处理
admin@hpc-1:~$ curl -X POST -u admin:admin -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8090/abc-api
Map printed successfully
admin@hpc-1:~$ 

额外知识点

  • flag的参数,即可以用空格也可以用=连接flag和赋值(-p=8090 和 -p 8090等价)
  • 只有bool类型是例外,只能是用=
本例中,默认指定authEnabled 为false下面用法表示false
(1)$ ./http_rpc_server -p=8090 -a=false
(2)$ ./http_rpc_server -p=8090 下面用法表示true
(1)$ ./http_rpc_server -p=8090 -a=true
(2)$ ./http_rpc_server -p=8090 -a
(3) ./http_rpc_server -p=8090 -a <随便什么非空格字符,甚至可以是false>
http://www.yayakq.cn/news/669509/

相关文章:

  • 网站建设推广优化手机类网站设计
  • 到底建手机网站还是电脑网站优惠劵精选网站怎么做
  • 网站建设公司薪资网站设置首页连接分类页的视频教程
  • 网站建设与管理维护说课做网站的步骤视频
  • 电商网站项目建设wordpress充值会员
  • 青岛制作网站软件加强健康养老网站建设
  • 可以自己做网站优化吗免费制作的企业网站
  • 二级a做爰片免费网站做高仿网站
  • 免费房地产网站模板wdlinux wordpress
  • 中企动力初期做的网站杭州的电商网站建设
  • 成都淮州新城建设投资有限公司网站网站开发公司怎么建服务器
  • html5开发的网站用图片做简单网站
  • 邯郸景区网站制作怎样选择高性价比的建站公司
  • 益阳网站开发公司什么软件可以做企业网站
  • 网站建设的软件平台营销型网站工程
  • 电子商务网站建设与管理课程论文做网站合同模板
  • 网站建设的针对对象智慧城市
  • 织梦做的网站织梦修改网页模板陕西工程项目信息网
  • 网站开发制作全包施工企业安全生产考核评定等级分为
  • 同学聚会怎么样做网站怎么制作网站网页
  • 希音电商网站网页制作软件有那些
  • 建站优化一条龙导航栏网站建站
  • 福建省交通建设质量安全监督局网站公司开发个网站有哪些
  • 网站建设网站建设哪里有网站设计制作一条龙多少钱
  • 网站关键词做排名不分安全证查询官网
  • 出站链接对网站有什么影响做产品类网站
  • 网站托管维护合同北京蓝杉网站建设公司
  • 珠海网站开发哪家好17网一起做网店潮汕池尾
  • 做网站 写脚本是什么wordpress的文章插件
  • 试百客 专业做试用的网站学做网站多少钱