惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

文章列表 on polarisxu

通过一个例子让你彻底掌握 Go 工作区模式 这道题正确率竟然只有 22% Go 开源项目推荐:一个简单的 Go 练手项目 go test 如何禁用缓存? Go1.18 快讯:constraints 包被移除标准库 跟着 Go 作者学泛型 「2022 版」轻松搞定 Go 开发环境 鹅厂小哥用行动反对加班:程序员加班能被终结吗? Go 为什么选择 Gopher 作为吉祥物? 本地如何配置多个 GitHub/Gitee 账号? 为 Java 开发者准备的 Go 教程 02:Java 有而 Go 无 GitHub 发现了 studygolang 项目依赖的漏洞 Typora 宣布收费后,这款开源 Markdown 编辑器火了 为 Java 开发者准备的 Go 教程 01:漫游了 我的 2021 年终总结 泛型版 singleflight:Go 中如何防止缓存击穿? 2021 年你写了多少代码?这个 Go 工具帮你统计 Go1.18 新特性:TryLock Go 泛型入门教程 程序员瑞士军刀:各种结构的转换工具 终于有 Go 版的 Elasticsearch 了 Go泛型系列:maps 包讲解 Go 1.18 中的 any 是什么? Go1.18 快讯:新的 IP 包 Go编程模式:详解函数式选项模式 Go泛型系列:slices 包讲解 Go泛型系列:Go1.18 类型约束那些事 Go1.18 快讯:Module 工作区模式 Go1.18 快讯:新增的 Cut 函数太方便了 Go1.18 快讯:废弃了这个 API Go1.18 快讯:新增字符串 Clone API Go:如何获得项目根目录? Go 如何获取和设置环境变量 重磅变动:更快找到微信公众号里的Go文章 Go 这样设置版本号:我们的项目也可以 假期结束,推荐 2 本 manning 出的 Go 图书 Go Fiber 框架系列教程 04:测试应用 Go Fiber 框架系列教程 03:中间件 Go泛型系列:提前掌握Go泛型的基本使用 推荐一个 Go GUI 实战项目 Go Fiber 框架系列教程 02:详解相关 API 的使用 Go Fiber 框架系列教程 01: 和 Express 对比学习 Go Module:私有不合规库怎么解决引用问题 Go1.17 新特性:go get 变了 Go1.17 新特性:testing 包的相关变化 StackOverflow 上关于 Go select 死锁的问题 新书推荐:用 Gin 框架构建分布式应用 Go 官网要变天。。。 Gin 这是要成为 Go 官方框架? 扬眉吐气:刚刚,Go 已经默认支持泛型了 Go 1.17 新特性:Module 有哪些变化? Go 第三方库推荐:类型转换如此简单 担心密码提交到 GitHub?建议使用这个 Go 开源工具 Go 的时间格式化为什么是 2006-01-02 15:04:05? GitHub 为 Go 社区带来安全支持 Go开源项目推荐:500行代码确认请求时间花在哪 一道关于 len 函数的诡异 Go 面试题解析 厉害了我的 Go:推荐系统都有开源实现 Go1.17 新特性:新版构建约束 这个工具真好:看看你的Go项目依赖有无漏洞 网友很强大,发现了Go并发下载的Bug Rust 劝退系列 09:函数 Go项目实战:一步步构建一个并发文件下载器 这本 Go 新书挺期待的:100 个常见错误 Go 启用新的官方问答社区 这是要干嘛?!微软招 Go 编译器全职开发人员 Go1.17 快报之标准库越来越注重易用性 Go1.17 新特性之切片变数组 回顾 Go 官网的演变史 站长8年前的Go代码竟然进入大厂的项目里了 Go图书翻译:一个好消息,一个坏消息 不怕烂尾!决定组织翻译这本 Go 图书 Rust 劝退系列 08:模式匹配 一本花了2.5年写成的Go免费在线图书 被黑惨了:一句话,说明自己会 Go,咋整? Go1.16 中的新函数 signal.NotifyContext 怎么用? Go 1.17 新特性提前学之测试执行随机化 Rust 劝退系列 07:流程控制 官方的 Go 多版本管理:使用和原理 Rust新书:给你一个劝退的理由 周刊题解:常量表达式这个规则应该了解下 盘点那些使用 Go 语言的国外公司 编写了50万行Go代码是一种什么体验 Rust 劝退系列 06:常量 Uber 使用 Go 的规模这么大?!都自己定制的 Go 编译器了 Go Team Leader — rsc 大神新开源了一个库,增强模板功能 再一次看到了 Go 的节制:int128 类型要不要支持? Rust 劝退系列 05:复合数据类型 「卷」有理论依据:海勒姆定律—Go又是怎么卷的 Go 真的也可以进行 GUI 开发:还有这样的图书呢 Rust 劝退系列 04:基本数据类型 我的 Go 语言书单 Rust 劝退系列 03:变量 我又来推荐免费 Go 新书了:一本用 Go 讲架构的书 注释竟然还有特殊用途?一文解惑 //go:linkname 指令 这个功能,公众号、微信群会不会被玩坏? 一道 Go 闭包题,面试官说原来自己答错了:面别人也涨知识 Rust 劝退系列 02:第一个 Rust 程序 Rust 劝退系列 01:打造开发环境 答应我,这次一定彻底搞懂 Go 中的类型别名
Nginx 竟然也有 playground — Go 语言构建的
2021-11-21 · via 文章列表 on polarisxu

大家好,我是 polarisxu。

曾几何时,playground 似乎成了新语言的标配:Go 发布就带有 https://play.golang.org/,Rust 发布也有 https://play.rust-lang.org/。你想过 Nginx 也有一个 playground 吗?你可以通过它方便的测试 Nginx 配置。

今天发现,还真有一个,地址:https://nginx-playground.wizardzines.com。关键是,后端使用 Go 构建的。

以下是该网址的截图:

Nginx Playground

本文简单介绍下这个 playground。

01 如何使用

打开这个网站后,在左侧,你可以写 Nginx 配置,在右上角可以通过 curl 命令或 http 命令(这是 httpie)来向该 Nginx 实例发送 HTTP 请求。

然后点击右上角的“Run”,成功后,在右下角会输出:

1)如果 Nginx 启动成功,输出执行命令的结果;

2)如果 Nginx 无法启动(配置出错了),则会输出 Nginx 错误日志。

02 原理

这个网站使用的技术如下:

1)前端使用 vue.js 和 tailwind;

2)后端就一个 API endpoint,使用 Go 语言构建。它只做 1 件事,即运行 Nginx 配置。

后端的完整代码见这里:https://gist.github.com/jvns/edf78e7775fea8888685a9a2956bc477

当你单击“Run”时,Go 后端会执行以下操作:

  1. 将配置写入临时文件
  2. 创建一个新的网络命名空间 ( ip netns add $RANDOM_NAMESPACE_NAME)
  3. 在端口 777 上启动 go-httpbin ,以便可以在 nginx 配置中使用它作为 backend(如上面截图中的 proxy_pass 地址)
  4. 启动 Nginx
  5. 等待 100 毫秒以确保 nginx 启动完成,如果失败则将 nginx 的错误日志返回给客户端
  6. 运行用户请求的命令(并确保命令以curl或开头http
  7. 返回命令的输出
  8. 完毕

Go 后端一共 100 多行代码,逻辑处理代码 70 行左右,对实现感兴趣的可以读一下。

03 小结

这个网站的作者写了一篇文章介绍它,包括安全问题、性能问题等,有兴趣的可以查看:https://jvns.ca/blog/2021/09/24/new-tool--an-nginx-playground/。另外,还有一个 Nginx location match 测试的网址:https://nginx.viraptor.info/

为了方便无法访问上面 Go 代码的同学,我将完整 Go 代码贴在下面:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"syscall"
	"time"
)

type RunRequest struct {
	NginxConfig string `json:"nginx_config"`
	Command     string `json:"command"`
}

type RunResponse struct {
	Result string `json:"result"`
}

func main() {
	rand.Seed(time.Now().UnixNano())
	http.Handle("/", wrapLogger(Handler{runHandler}))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func runHandler(w http.ResponseWriter, r *http.Request) error {
	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "*")
	if r.Method != "POST" {
		// OPTIONS request
		return nil
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return fmt.Errorf("failed to read body: %s", err)
	}
	var req RunRequest
	json.Unmarshal([]byte(body), &req)

	// write config
	file, err := os.CreateTemp("/tmp", "nginx_config")
	errorFile, err := os.CreateTemp("/tmp", "nginx_errors")
	if err != nil {
		return fmt.Errorf("failed to create temp file, %s", err)
	}
	file.WriteString(req.NginxConfig)
	file.Close()
	defer os.Remove(file.Name())
	defer os.Remove(errorFile.Name())

	// set up network namespace
	namespace := "ns_" + randSeq(16)
	if err := exec.Command("ip", "netns", "add", namespace).Run(); err != nil {
		return fmt.Errorf("failed to create network namespace: %s", err)
	}
	defer exec.Command("ip", "netns", "delete", namespace).Run()

	if err := exec.Command("ip", "netns", "exec", namespace, "ip", "link", "set", "dev", "lo", "up").Run(); err != nil {
		return fmt.Errorf("failed to create network namespace: %s", err)
	}

	// start httpbin
	httpbin_cmd := exec.Command("ip", "netns", "exec", namespace, "go-httpbin", "-port", "7777")
	if err := httpbin_cmd.Start(); err != nil {
		return fmt.Errorf("failed to start go-httpbin: %s", err)
	}
	defer kill(httpbin_cmd)

	// start nginx
	nginx_cmd := exec.Command("ip", "netns", "exec", namespace, "nginx", "-c", file.Name(), "-e", errorFile.Name(), "-g", "daemon off;")
	if err != nil {
		return fmt.Errorf("failed to get pipe: %s", err)
	}
	ch := make(chan error)
	go func() {
		ch <- nginx_cmd.Run()
	}()

	// Check for errors
	select {
	case <-ch:
		logs, _ := os.ReadFile(errorFile.Name())
		return fmt.Errorf("nginx failed to start. Error logs:\n\n %s", string(logs))
	case <-time.After(100 * time.Millisecond):
		defer term(nginx_cmd)
		break
	}

	// run curl
	curlArgs := strings.Split(strings.TrimSpace(req.Command), " ")
	if curlArgs[0] != "curl" && curlArgs[0] != "http" {
		return fmt.Errorf("command must start with 'curl' or 'http'")
	}
	curlCommand := append([]string{"netns", "exec", namespace}, curlArgs...)
	output, _ := exec.Command("ip", curlCommand...).CombinedOutput()

	// return response
	resp := RunResponse{
		Result: string(output),
	}
	response, err := json.Marshal(&resp)
	if err != nil {
		return fmt.Errorf("failed to marshal json, %s", err)
	}

	w.Header().Add("Content-Type", "application/json")
	w.Write(response)

	return nil
}

func wrapLogger(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rw := &responseWrapper{w, 200}
		start := time.Now()
		handler.ServeHTTP(rw, r)
		elapsed := time.Since(start)
		log.Printf("%s %d %s %s %s", r.RemoteAddr, rw.status, r.Method, r.URL.Path, elapsed)
	})
}

func term(cmd *exec.Cmd) {
	if cmd.Process != nil {
		cmd.Process.Signal(syscall.SIGTERM)
	}
}
func kill(cmd *exec.Cmd) {
	if cmd.Process != nil {
		cmd.Process.Kill()
	}
}

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func randSeq(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}