通过 Golang 学习 http,几行代码实现 http proxy

这个 Github 作为通过 Golang 学习 http 中的其中一篇教程,非常简单明了。

其中关于 http proxy 代理用户校验部分代码如下,r.Header.Get("Proxy-Authorization") 从 request 的 header 中获取 ‘Proxy-Authorization’ 并将其通过 base64 解码获取用户名和密码进行校验。

若失败则直接将 http status code 通过 w.WriteHeader 返回给用户端。

func basicAuth(w http.ResponseWriter, r *http.Request, users []User) bool {

	var auth = r.Header.Get("Proxy-Authorization")

	if ms := strings.Split(auth, " "); len(ms) == 2 && ms[0] == "Basic" {

		// check user:password
		up, err := base64.StdEncoding.DecodeString(ms[1])

		if err == nil {
			if ms := strings.Split(string(up), ":"); len(ms) == 2 {

				var user, password = ms[0], ms[1]
				var ok = false

				for _, u := range users {
					if u.UserId == user && u.Password == password {
						ok = true
						break
					}
				}

				if ok {
					return true
				}
			}
		}
		w.WriteHeader(http.StatusForbidden)
	} else {

		w.WriteHeader(http.StatusProxyAuthRequired)
		w.Header().Set("Proxy-Authenticate", `Basic realm="Http Proxy"`)
	}

	return false
}

https/http proxy, with Basic Authentication

comments powered by Disqus

Tags

abcs accept acid activemq affinity algorithm allocation android array async aws b+tree b-tree backoff benchmark best-practices bfs big-o bigquery bind bitcount blog break broker bubble buffer cache cap cert cgroups channel citus class classmethod cluster concurrency config consumer container cookie cors crawler cronjob csrf ctr data-science data-structure database datadog dataflow datascience decorator defer dfs distributed django dns docker double-shipping drf ecosia elastic-search enumerate epoll extra facebook-pixel financial-report flask flutter forward-proxy freelance frp garbage-collector gc gcp generator get gil git golang goroutine graphql ha handbook haproxy hash hash-slot hashring hashtable hpa http http-auth http-proxy http_proxy https index innodb instagram intergration interview ios javascript jinja2 jobboard jwt k8s kafka kibana kqueue label lambda layer4 layer7 lean levels.io linked-list linux list listen loadbalancer logs long-tail lru marketing master matplotlib memory merge metaclass metaprogramming metrics metrics-server microservices mitm model mq myisam mysql namespace nat netflix network-extension nginx nodejs nomad nosql npm oodesign openssl optimization orm pandas parallelism parkinglot patroni permission pg pipeline pixelme post postgresql postresql prefetch_related prerender process proxy proxycommand put pvm python queue rabbitmq rbac react-native rebase redis redis-cluster replication resource rest restfulapi retargeting retry revenue reverse-proxy rocketmq saas scaleable search-engine security select seo serverless service session set shadosocks shadowsocks shard sharding shell shopify sigint signal sigterm slack slave slow-query sniper sns socket socks5 source-code spa sql sqlalchemy sqs ssh ssl ssl-pinning stack startup state stateful stateless staticmethod string struct swift switch syscall system-design systemctl tcp tcp-proxy thread tmpreaper token traefik trustkit tunning type typeform udp variable vc vpn vuejs web web-development where yarn zset 削峰 宽索引 异步 窄索引 解耦 跨域 跳板机



Archives

2019 (137)
0001 (1)