Golang部署程序时Buildfile和Procfile的配置指南

Golang部署程序时Buildfile和Procfile的配置指南 我的问题与这个问题类似,并且我已经按照该问题最后一条评论中的建议操作:将简单的GoLang应用程序部署到AWS Elastic Beanstalk - #3 by awais。但我仍然遇到以下错误,我知道在这个过程中我一定做错了什么

application.go:7:2: 在任何路径中都找不到包 “github.com/gorilla/mux

我的代码结构是这样的 46 AM

我的 build.sh

#!/bin/bash

go get github.com/gorilla/mux
go build -o bin/application application.go

我的 buildfile.text

make: ./build.sh

我的 Procfile.text

web: bin/application

我是新手,但我唯一能想到的是可能buildfile和/或Procfile可能需要不同的扩展名。

然后我使用 zip …/eb.zip -r * .[^.]* 来压缩我的项目并上传到AWS,但上传完成后总是失败。提示信息是无法找到包 github.com/gorilla/mux。在这个过程中我是否遗漏了什么……我的代码在本地可以编译,代码如下:

package main

import (
	"net/http"
	"./Controllers"
	"runtime"
	"github.com/gorilla/mux"
	"time"
)

func main() {
        println(runtime.Version())
	runtime.GOMAXPROCS(runtime.NumCPU())
	r := mux.NewRouter()
	r.HandleFunc("/testping", Controllers.TestPing)
	http.Handle("/", r)

	r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("public"))))
	srv := &http.Server{
		ReadTimeout:  20 * time.Second,
		WriteTimeout: 20 * time.Second,
		IdleTimeout:  120 * time.Second,
		Addr:         ":5000",
	}

	srv.ListenAndServe()
}

更多关于Golang部署程序时Buildfile和Procfile的配置指南的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

对我来说,https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/go-environment.html 文档读起来像是当存在 bin/application.go 文件时,构建文件和进程文件会被忽略,因为文档在列举应用程序构建方式的要点中首先提到了这一点。

请尝试重命名该文件并相应修改您的构建文件。

免责声明:本人从未使用过AWS,以上理解完全基于对上述链接文档的解读。

更多关于Golang部署程序时Buildfile和Procfile的配置指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在AWS Elastic Beanstalk中部署Go应用时,依赖管理需要确保在构建环境中正确获取依赖包。从错误信息看,构建环境无法找到github.com/gorilla/mux包,这通常是因为构建环境没有正确设置GOPATH或依赖管理方式不当。

以下是解决方案:

  1. 使用Go Modules进行依赖管理(推荐方式): 在项目根目录创建go.mod文件,这样构建环境会自动处理依赖。
# 在本地项目目录中初始化Go模块
go mod init your-app-name

这会生成go.mod文件,然后运行:

go mod tidy

这会自动添加缺失的依赖并移除未使用的依赖。

  1. 修改build.sh脚本: 确保在构建前设置正确的环境变量并使用Go Modules:
#!/bin/bash

# 启用Go Modules
export GO111MODULE=on

# 下载依赖
go mod download

# 构建应用
go build -o bin/application application.go
  1. 确保文件扩展名正确
  • Buildfile应该命名为Buildfile(无扩展名)
  • Procfile应该命名为Procfile(无扩展名)
  1. 完整的项目结构应该包含
your-app/
├── Buildfile
├── Procfile
├── build.sh
├── go.mod
├── go.sum
├── application.go
└── Controllers/
    └── controllers.go
  1. 修改application.go中的导入路径: 避免使用相对路径导入,改为使用完整的模块路径:
package main

import (
	"net/http"
	"your-app-name/Controllers"  // 使用模块路径
	"runtime"
	"github.com/gorilla/mux"
	"time"
)

// 其余代码保持不变
  1. Buildfile内容
make: ./build.sh
  1. Procfile内容
web: bin/application
  1. 构建脚本执行权限: 确保build.sh有执行权限:
chmod +x build.sh

使用这种方式,当你在AWS Elastic Beanstalk中部署时,构建环境会自动识别Go Modules并正确处理依赖关系。压缩项目时确保包含所有必要的文件:

zip -r ../eb.zip * .[^.]*

这样应该能解决依赖包找不到的问题。

回到顶部