部署go项目到linux服务器(简易版)

部署go项目到linux服务器(简易版)

前提条件:

  1. 本地已经有go语言的运行环境,可以参考GO语言下载与安装
  2. 有编辑器(如vscode)
  3. 有服务器,如阿里云服务器
  4. 服务器安装了宝塔面板

本地新建项目并运行

新建一个main.go文件

go 复制代码
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
)

type Response struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

func main() {
	// 设置路由
	http.HandleFunc("/", handleRequest)
	http.HandleFunc("/api/test", handleTestRequest)

	// 获取端口(默认为 8080)
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	// 启动服务器
	log.Printf("Server starting on :%s...", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	response := Response{
		Status:  "success",
		Message: "Welcome to the test API",
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

func handleTestRequest(w http.ResponseWriter, r *http.Request) {
	var response Response

	switch r.Method {
	case http.MethodGet:
		response = Response{
			Status:  "success",
			Message: "GET request received",
			Data: map[string]string{
				"method":  "GET",
				"example": "This is a GET response",
			},
		}
	case http.MethodPost:
		var requestData map[string]interface{}
		if err := json.NewDecoder(r.Body).Decode(&requestData); err != nil {
			response = Response{
				Status:  "error",
				Message: "Invalid JSON payload",
			}
			w.WriteHeader(http.StatusBadRequest)
		} else {
			response = Response{
				Status:  "success",
				Message: "POST request received",
				Data: map[string]interface{}{
					"method":  "POST",
					"payload": requestData,
				},
			}
		}
	default:
		response = Response{
			Status:  "error",
			Message: "Method not allowed",
		}
		w.WriteHeader(http.StatusMethodNotAllowed)
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

本地运行:go run main.go

如果正常打印Server starting on :8080...,则启动成功

打包项目

为了在linux服务器正常运行项目,我们需要在打包时设置目标为linux

bash 复制代码
# CMD 命令提示符
set GOOS=linux
set GOARCH=amd64
go build -o myapp-linux main.go

# PowerShell
$env:GOOS = "linux"
$env:GOARCH = "amd64"
go build -o myapp-linux main.go

逐行执行上述命令,即可完成打包,在同级目录输出一个可执行文件myapp-linux

上传到服务器

将可执行文件myapp-linux上传到服务器的某个目录下,以/www/serverFiles/goServer为例。然后在宝塔面板中新建一个go服务。

第一步:

第二步:

第三步:

访问接口

在浏览器输入${你上面填的的ip地址或域名} + /api/test,如果提示{"status":"success","message":"GET request received","data":{"example":"This is a GET response","method":"GET"}},则服务启动成功。

遇到的问题

  • 如果提示域名绑定失败,域名已被占用,则可以检查一下宝塔面板的本站其他项目,是否用了这个域名。
  • 如果部署后访问提示502 bad getway,则检查一下宝塔面板的配置文件中的端口,是不是跟项目里设置的端口一致(本文这个项目是8080)。
相关推荐
@yanyu6661 分钟前
springboot实现查询学生
java·spring boot·后端
酷爱码31 分钟前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
AI小智1 小时前
Google刀刃向内,开源“深度研究Agent”:Gemini 2.5 + LangGraph 打造搜索终结者!
后端
java干货1 小时前
虚拟线程与消息队列:Spring Boot 3.5 中异步架构的演进与选择
spring boot·后端·架构
一只叫煤球的猫2 小时前
MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
后端·sql·mysql
写bug写bug2 小时前
如何正确地对接口进行防御式编程
java·后端·代码规范
不超限3 小时前
Asp.net core 使用EntityFrame Work
后端·asp.net
豌豆花下猫3 小时前
Python 潮流周刊#105:Dify突破10万星、2025全栈开发的最佳实践
后端·python·ai
忆雾屿4 小时前
云原生时代 Kafka 深度实践:06原理剖析与源码解读
java·后端·云原生·kafka