Golang运行server.go时启动报错原因排查
Golang运行server.go时启动报错原因排查
command-line-arguments
.\server.go:16:2: undefined: AddApproutes
server.go
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
log.Println("Server will start at http://localhost:8000/")
route := mux.NewRouter()
AddApproutes(route)
log.Fatal(http.ListenAndServe(":8000", route))
}
routes.go
package main
import (
"log"
"github.com/gorilla/mux"
)
func AddApproutes(route *mux.Router) {
log.Println("Loadeding Routes...")
route.HandleFunc("/", RenderHome)
route.HandleFunc("/sendEmail", SendEmailHandler).Methods("POST")
log.Println("Routes are Loaded.")
}
更多关于Golang运行server.go时启动报错原因排查的实战教程也可以访问 https://www.itying.com/category-94-b0.html
5 回复
由于它们位于同一个包中,您只需要在运行或构建命令行中指定 routes.go 文件,例如 go run main.go routes.go。
func main() {
fmt.Println("hello world")
}
更多关于Golang运行server.go时启动报错原因排查的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
当我添加 go run main.go routes.go 时,出现此错误。
command-line-arguments
.\routes.go:14:32: 未定义:RenderHome .\routes.go:16:46: 未定义:SendEmailHandler
你需要创建 RenderHome 和 SendEmailHandler 函数。例如
func RenderHome(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Hello, World!")
}
func SendEmailHandler(w http.ResponseWriter, r *http.Request) {
}
这个错误是因为Go编译器在编译server.go时找不到AddApproutes函数的定义。虽然你在routes.go中定义了该函数,但编译器没有同时编译这两个文件。
解决方案:
- 确保两个文件在同一个包中(都是
package main) - 使用正确的编译命令:
# 编译整个包
go build .
# 或者直接运行
go run .
- 如果使用
go run server.go单独运行一个文件,需要指定所有相关文件:
go run server.go routes.go
- 或者使用通配符:
go run *.go
正确的工作目录结构应该是:
your-project/
├── server.go
├── routes.go
└── go.mod
检查go.mod文件是否存在,如果没有需要初始化:
go mod init your-module-name
go mod tidy
完整示例:
# 初始化模块
go mod init myserver
# 添加依赖
go get github.com/gorilla/mux
# 运行所有go文件
go run *.go
这样编译器就会同时编译server.go和routes.go,找到AddApproutes函数的定义。


