Go 项目从开发到部署笔记

今天完整记录了从 Go 开发环境搭建、接口实现、打包部署到 Linux 服务器,以及 Nginx 代理与防火墙排查的全过程,适合入门学习和部署参考。

一、环境安装与配置

1. 安装 Go
  • 安装路径:D:\Go

  • 验证:

    go.exe version

    输出: go version go1.25.1 windows/amd64

  • 配置环境变量:将 D:\Go\bin 添加到 PATH

2. 初始化项目

cd "C:\Users\18272\Desktop\Go"

go mod init go-hope

  • 项目结构:

go-hope/

├── main.go

├── go.mod

二、实现基础 Go 服务

1. main.go 示例
go 复制代码
package main

import (
    "fmt"
    "net/http"
)

func main() {
    InitDB() // 初始化数据库

    // 注册路由
    http.HandleFunc("/api/login", LoginHandler)
    http.HandleFunc("/api/register", RegisterHandler)
    http.HandleFunc("/api/delete", DeleteHandler)
    http.HandleFunc("/api/users", ListUsersHandler)

    port := "8080"
    fmt.Printf("Server started at http://localhost:%s\n", port)
    if err := http.ListenAndServe(":"+port, nil); err != nil {
        fmt.Println("Server failed:", err)
    }
}
2. 数据库操作
  • 使用 MySQL,创建数据库与 users 表:
sql 复制代码
CREATE DATABASE go_hope;
USE go_hope;
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) UNIQUE,
    password VARCHAR(255)
);
INSERT INTO users(username, password) VALUES('admin','');
  • 安装 MySQL Go 驱动:

go get -u github.com/go-sql-driver/mysql

三、测试接口

  • 使用 curl 或 Apifox 测试:

curl http://127.0.0.1:8080/api/users

// [{"id":1,"username":"admin","password":""}]

  • 注意:

    • 直接访问 http://127.0.0.1:8080 可用

    • 访问 80 端口(Nginx)如果没配置反向代理会 404

    • Apifox 前置脚本 fetch is not defined 是 JS 环境问题,可忽略

四、Go 服务打包与部署

1. Windows 下交叉编译 Linux 可执行文件
复制代码
# PowerShell
$env:GOOS = "linux"
$env:GOARCH = "amd64"
cd /对应目录
go build -o go-hope

输出 go-hope 可执行文件,直接上传到 Linux 服务器即可运行。

2. 上传并运行
bash 复制代码
# 上传到 /home/dist
scp go-hope root@your-server:/home/dist

# 登录服务器
cd /对应目录
后台常驻运行
* log.txt 会记录日志
* & 表示后台运行
nohup ./go-hope > log.txt 2>&1 &

五、防火墙问题(502 Bad Gateway 排查)

  1. 502 原因:外网访问 8080 失败
  2. 排查方法:
bash 复制代码
# 检查端口是否监听
netstat -tlnp | grep 8080

# 测试本机访问
curl http://127.0.0.1:8080/api/users
  1. 解决:
bash 复制代码
# Ubuntu/Debian
sudo ufw allow 8080/tcp
sudo ufw status

# 或 iptables
sudo iptables -I INPUT -p tcp --dport 8080 -j ACCEPT


解释:云厂商安全组开了 8080 端口,但 Linux 系统防火墙默认阻止外部访问,所以需要本机放行。

七、总结经验与注意事项

  1. Go 项目部署不像 Java 可直接打 jar,需要编译成目标系统的可执行文件。

  2. 外网访问要同时检查:

    云安全组是否放行端口

    本机防火墙是否允许端口

  3. Nginx 配置:

    仅在需要统一域名或做静态页面 + API 反向代理时才配置

    对粘贴板动态路由无需 Nginx 干预

  4. 常见问题:

    502 → 防火墙或代理问题

    404 → Nginx root 或 proxy_pass 路径错误

    fetch is not defined → Apifox 前置脚本 JS 环境问题

最后再贴一下我的nginx

nginx之前有部署一个粘贴板项目 访问 地址/xxx 任何地址都是新建一块粘贴板 刚开始和这个接口冲突了 导致访问接口/api/users 创建名称为/api/users的粘贴板

nginx 复制代码
user www www;
worker_processes auto;
error_log /www/wwwlogs/nginx_error.log crit;
pid /www/server/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;

stream {
    log_format tcp_format '$time_local|$remote_addr|$protocol|$status|$bytes_sent|$bytes_received|$session_time|$upstream_addr|$upstream_bytes_sent|$upstream_bytes_received|$upstream_connect_time';
    access_log /www/wwwlogs/tcp-access.log tcp_format;
    error_log /www/wwwlogs/tcp-error.log;
    include /www/server/panel/vhost/nginx/tcp/*.conf;
}

events {
    use epoll;
    worker_connections 51200;
    multi_accept on;
}

http {
    include       mime.types;
    #include luawaf.conf;

    include proxy.conf;
    lua_package_path "/www/server/nginx/lib/lua/?.lua;;";

    default_type application/octet-stream;

    server_names_hash_bucket_size 512;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 50m;

    sendfile on;
    tcp_nopush on;
    keepalive_timeout 60;
    tcp_nodelay on;

    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;

    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/json image/jpeg image/gif image/png font/ttf font/otf image/svg+xml application/xml+rss text/x-js;
    gzip_vary on;
    gzip_proxied expired no-cache no-store private auth;
    gzip_disable "MSIE [1-6]\.";

    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_conn_zone $server_name zone=perserver:10m;

    server_tokens off;
    access_log off;

    server {
        listen 888;
        server_name phpmyadmin;
        index index.html index.htm index.php;
        root /www/server/phpmyadmin;

        allow 127.0.0.1;
        allow ::1;
        deny all;

        #error_page 404 /404.html;
        include enable-php.conf;

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
            expires 30d;
        }

        location ~ .*\.(js|css)?$ {
            expires 12h;
        }

        location /api/ {
            proxy_pass http://127.0.0.1:8080/;  # 注意末尾必须有 /
            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_buffering off;  # 可选,避免缓存干扰
        }

        location ~ /\. {
            deny all;
        }

        access_log /www/wwwlogs/access.log;
    }

    include /www/server/panel/vhost/nginx/*.conf;
}
  • /api/ 独立转发 Go 服务。

  • 粘贴板 / 默认 fallback 到 paste.php。

  • PHP 也在 / 下生效,不会被 /api/ 干扰。

  • 粘贴板是明确的 fallback,PHP location 的SCRIPT_FILENAME 直接对应 /home/dist/paste.php。

相关推荐
小树懒(-_-)2 小时前
SEO:Java项
java·开发语言
聪明的笨猪猪2 小时前
Java “线程池(1)”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
胖咕噜的稞达鸭3 小时前
二叉树进阶面试题:最小栈 栈的压入·弹出序列 二叉树层序遍历
开发语言·c++
wzg20163 小时前
pyqt5 简易入门教程
开发语言·数据库·qt
kfepiza3 小时前
`modprobe`命令 与 `KVM`模块 笔记251006
linux·笔记
心静财富之门3 小时前
【无标题】标签单击事件
开发语言·php
草莓熊Lotso3 小时前
揭开 C++ vector 底层面纱:从三指针模型到手写完整实现
开发语言·c++
小秋学嵌入式-不读研版4 小时前
C56-字符串拷贝函数strcpy与strnpy
c语言·开发语言·笔记
hui函数4 小时前
python全栈(基础篇)——day04:后端内容(字符编码+list与tuple+条件判断+实战演示+每日一题)
开发语言·数据结构·python·全栈