You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用NGINX反向代理Go Web服务器?求具体配置示例

使用NGINX反向代理Go Web服务器的配置方案

可行性说明

完全可以用NGINX作为反向代理转发请求到你的Go Web服务器,这是生产环境中常用的部署方式——NGINX可负责静态资源分发、SSL证书管理、负载均衡等工作,让你的Go服务器专注处理业务逻辑。

前置条件

确保你的Go Web服务器正常运行:

  • 你的代码基于gearbox框架,监听7070端口
  • 启动服务后,访问http://localhost:7070能正常显示TODO页面

NGINX配置步骤

  1. 创建站点配置文件
    进入NGINX站点配置目录(通常为/etc/nginx/sites-available/),新建go-todo.conf文件,内容如下:

    server {
        listen 80;
        server_name localhost; # 可替换为你的实际域名
    
        location / {
            # 转发请求到Go服务器的7070端口
            proxy_pass http://localhost:7070;
            # 传递必要请求头,确保Go服务器获取正确的请求信息
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    
  2. 启用配置并验证

    • 创建软链接到启用目录:ln -s /etc/nginx/sites-available/go-todo.conf /etc/nginx/sites-enabled/
    • 测试配置语法:nginx -t,输出test is successful则配置无误
    • 重启NGINX生效:systemctl restart nginx

验证结果

配置完成后,直接访问http://localhost(或你的域名),即可看到Go服务器生成的TODO页面,请求会通过NGINX自动转发到7070端口的Go服务。

你的Go服务器代码

package main

import (
    "html/template"
    _"net/http"
    gear "github.com/gogearbox/gearbox"
)

type Todo struct {
    Title string
    Done  bool
}

type TodoPageData struct {
    PageTitle string
    Todos     []Todo
}

func main() {
    tmpl := template.Must(template.ParseFiles("layout.html"))

    var Gear = gear.New()

    Gear.Get("/", func(ctx gear.Context) {
        data := TodoPageData{
            PageTitle: "My TODO list",
            Todos: []Todo{
                {Title: "Task 1", Done: false},
                {Title: "Task 2", Done: true},
                {Title: "Task 3", Done: true},
            },
        }

        tmpl.Execute(ctx.Context() , data)
    })

  Gear.Start(":7070")
}

你的layout.html页面

<h1>{{.PageTitle}}</h1>

<ul>

    {{range .Todos}}

        {{if .Done}}

            <li class="done">{{.Title}}</li>

        {{else}}

            <li>{{.Title}}</li>

        {{end}}

    {{end}}

</ul>

内容的提问来源于stack exchange,提问作者Coding with Cyril

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 07:25:32