python做网站是不是特别慢/宁波seo推广定制
之前写的《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>
相关文章:

golang通过参数控制HTTP server是否使用基本认证
之前写的《golang实现一个BasicAuth的HTTP server》一定会做基本认证。 本例给出了如何通过启动时候指定的参数来控制是否做基本认证 代码对比和解释 给出与上一篇中源码的diff adminhpc-1:~/go/auth_http$ diff -ruN http_rpc_server.go_bak http_rpc_server.go --- http_rp…...

javaSwing坦克大战游戏
在游戏开发领域,坦克大战是一款经典的游戏,其简单而又耐玩的玩法吸引了无数玩家。而今,在Java编程技术的支持下,我们可以用Java Swing技术轻松实现这款经典游戏。本文将介绍如何使用Java Swing技术编写坦克大战游戏,并…...

【面试题】数据底层原理:Elasticsearch写入流程解析
前言:本篇博客将介绍Elasticsearch的数据底层原理,涉及数据写入的过程以及相关概念。我们将深入探讨buffer、translog、refresh、commit、flush和merge等核心概念,帮助您更好地理解Elasticsearch的数据存储机制。 写入数据的基本过程 Elast…...

牛客论坛spring initializer选用的构件
spring版本:2.1.5.RELEASE java版本:8 pom文件: <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-i…...

【Java程序设计】【C00385】基于(JavaWeb)Springboot的员工信息管理系统(有论文)
基于(JavaWeb)Springboot的员工信息管理系统 项目简介项目获取开发环境项目技术运行截图 博主介绍:java高级开发,从事互联网行业六年,已经做了六年的毕业设计程序开发,开发过上千套毕业设计程序,…...

【Linux进阶之路】理解UDP,成为TCP。
前言 学了TCP 和UDP之后,感觉UDP就像是初入职场的年轻人,两耳不闻 “窗外事”,只管尽力地把自己的事情做好,但收获的却是不可靠,而TCP更像是涉世极深的"职场老油条",给人的感觉就是 “城府极深&a…...

Linux实用操作
一,各类小技巧(快捷键) 强制停止 ctrlc强制停止 Linux某些程序的运行,如果想要强制停止它,可以使用快捷键ctrlc 命令输入错误,也可以通过快捷键ctrlc,退出当前输入,重新输入 退出、登出 ctrld退出或登出 可以通过快…...

OpenJudge - 12:加密的病历单
总时间限制: 1000ms 内存限制: 65536kB 描述 小英是药学专业大三的学生,暑假期间获得了去医院药房实习的机会。 在药房实习期间,小英扎实的专业基础获得了医生的一致好评,得知小英在计算概论中取得过好成绩后,主任又额外交给她一…...

QGIS编译(跨平台编译)057:FastCGI编译(Windows、Linux、MacOS环境下编译)
文章目录 1、FastCGI介绍2、FastCGI下载3、Windows下编译4、linux下编译5、MacOS下编译1、FastCGI介绍 FCGI 是 FastCGI 的缩写,是一种用于改善 CGI(Common Gateway Interface)性能的协议。在传统的 CGI 中,每次请求都需要启动一个新的进程来处理,这导致了较高的资源消耗和…...

jenkins+newman+postman持续集成环境搭建
一、Newman简介 Newman是一款基于Node.js开发的,可以运用postman工具直接从命令运行和测试postman集合 二、Newman应用 环境准备:js/ cnpm或npm配置好环境,执行如下命令 三、安装newman 验证是否安装成功,命令:newm…...

取消自动设置的开机自启动(pywin32库)请勿仿照!否则可能对电脑造成损害。
本文使用创作助手。 要取消Python程序的开机自启动,可以通过删除注册表中相应的注册表项来实现。请按照以下步骤进行操作: 打开Windows注册表编辑器:按下 Windows R 键,输入 regedit,然后按下回车键。 导航到注册表…...

金融投贷通(金融投资+贷款通)项目准备
金融投贷通(金融投资贷款通)项目准备 专业术语投资专业术语本息专业术语还款专业术语项目介绍三个子系统技术架构核心流程发布借款标投资业务 项目实施测试流程测试步骤 专业术语 投资专业术语 案例:张三借给李四5W,约定期满1年后…...

跟我学C++中级篇——STL的中的删除
一、介绍 在STL中一般删除的方式有两类,一种是使用全局的std::remove(remove_if类似),一种是使用容器自带的erase,前者其实并没有真正的删除数据,而后者则是在移动时,会有一些细节的处理,否则要么程序崩溃…...

js如何遍历查询一个颗树
近段时间去面试的时候,被面试官问到如何遍历查询一个颗树的时候,可能最近自己看了数据结构的书之后,隐隐约约就想到二叉树的三种排序(前序、中序、后序),但是当时自己没有想起这三种排序的名字,…...

【面试必备】针对一个案例,怎么测试
思考角度 测试用例设计万能公式功能测试(最重要)界面测试易用性测试性能测试安全性测试兼容性测试容错性测试 常见案例物品类水杯笔 软件类微信发送朋友圈功能 测试用例设计万能公式 在面试中经常会遇到的一类题是,给你一个具体的产品&#…...

vue3 hooks之事件广播(支持跨标签页)
/**** 同源下的全局事件总线,支持跨标签页通信* 第一步:注册事件* 第二步:广播事件* 第三步:处理事件*/// source:消息发起源href,将在跨标签页通信时传入 interface callback {(data: any, source: any): …...

go中validate包使用教程
文章目录 前言安装简单使用错误处理翻译器Validator库介绍校验语法常用标记自定义校验需求【校验车身颜色】前言 在go项目中,经常有校验数据合法性的需求,比如邮箱、年龄、车牌号、网址、字符串长度、金额、枚举范围等。一个好的校验包能帮我们少写很多ifelse,提高系统的可…...

canvas画带透明度的直线和涂鸦
提示:canvas画线 文章目录 前言一、带透明度的直线和涂鸦总结 前言 一、带透明度的直线和涂鸦 test.html <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content…...

linux命令 curl忽略https证书
curl https://www.baidu.com 会提示需要htttps证书,加 -k 即可,如下: curl -k https://www.baidu.com 如果要带头部,认证数据,加-H curl -s -k -H "Authorization: Bearer 651fasgassssgjage2" https:/…...

游戏引擎中网络游戏的基础
一、前言 网络游戏所面临的挑战: 一致性:如何在所有的主机内都保持一样的表现可靠性:网络传输有可能出现丢包安全性:反作弊,反信息泄漏。多样性:不同设备之间链接,比如手机,ipad&a…...

ES6(ECMAScript 6)中常用的知识点总结(包含示例代码)
ES6(ECMAScript 6)是JavaScript语言的最新版本,它在ES5的基础上做了很多增强和扩展,使JavaScript的编程模式更加现代化和优雅,不仅拓展了语言表达能力,也为编程带来了全新的编程范式和思维方式。在项目中使用ES6,让代码更加简洁、方便模块化和面向对象实现等&#x…...

老师人手必备的教学神器有哪些?这5款教学软件一定要知道!
教师职业生活中有哪些“神器”?对老师来说堪称神器的东西有很多,笔者虽不是老师,工作内容有所不同,但工作给人带来的心力消耗(心累/压力/焦虑)、身体上的疲惫(困)等等,这…...

华为机试题-核酸检测人数
题目 为了达到新冠疫情精准防控的需要,为了避免全员核酸检测带来的浪费,需要精准圈定可能被感染的人群。现在根据传染病流调以及大数据分析,得到了每个人之间在时间、空间上是否存在轨迹的交叉。现在给定一组确诊人员编号 (X1, X2, X3, …, n…...

SQLAlchemy模型映射提示declarative_base() takes 0 positional arguments but 1 was given
原码: #SQLAlchemy模型映射表结构. from sqlalchemy import create_engine,Column,Integer,String from sqlalchemy.ext.declarative import declarative_base# 数据库的变量 HOST 127.0.0.1 PORT 3306 DATA_BASE itbz USER root PWD 123456 DB_URL fmysqlpy…...

linux系统Kubernetes工具ingress暴露服务
Ingress Ingressingress详解创建 Ingress 资源部署 Ingress 控制器(Nginx)下载ingress controller创建ingress-controller测试ingress创建两个应用和service配置ingress转发文件 修改ingress转发类型 Ingress 暴露服务基于域名的虚拟主机 Ingress 》ing…...

centos2anolis
我的centos7原地升级到anolis7记录 注意:如果是桌面版请先卸载firefox,否则so文件冲突。 参考: CentOS 7和8Linux系统迁移到国产Linux龙蜥Anolis OS 8手册_disable pam_pkcs11 module in pam configuration-CSDN博客 关于 CentOS 迁移龙蜥…...

Cesium安装部署运行
目录 1.简介 2.Cesium项目下载 3.Cesium项目运行 4.cesium运行 1.简介 Cesium是国外一个基于JavaScript编写的使用WebGL的地图引擎。Cesium支持3D,2D,2.5D形式的地图展示,可以自行绘制图形,高亮区域,并提供良好的触摸支持,且支…...

【Android 内存优化】KOOM线程泄漏监控的实现源码分析
文章目录 线程monitor的流程怎么判断线程是否泄漏AddThreadJoinThreadExitThreadDetachThread 总结 前面我们通过研究KOOM的开源代码,研究了关于Java层和native层内存泄漏监控的实现原理。还剩下线程泄漏这部分没有进行分析,今天来补全它。整体下来&…...

【爬虫基础】第1讲 网络爬虫基本知识
什么是网络爬虫 网络爬虫(Web crawler)是一种自动化程序,用于在互联网上收集信息。它可以通过扫描和解析网页的超链接,自动访问网页并抓取所需的数据。网络爬虫常用于搜索引擎和数据采集工具中。 作用 通过有效的爬虫手段批量采…...

scrapy爬虫框架
scrapy爬虫框架 一、scrapy的概念作用和工作流程1、scrapy的概念2、scrapy框架的作用3、scrapy的工作流程(重点)3.1 回顾之前的爬虫流程3.2 改写上述流程3.3 scrapy的流程3.4 scrapy的三个内置对象3.5 scrapy中每个模块的具体作用 二、scrapy的入门使用1…...