如何使用外部的主函数构建一个程序?

huangapple go评论89阅读模式
英文:

How to build a program with a foreign main function?

问题

我正在写一个框架,并且希望将 HTTP 服务器的初始化部分作为该框架的一部分。基本上,我有一个名为 "internal" 的包,如下所示,该包被框架中间件导入:

package internal

import (
    "net/http"
    "log"
)

func main() {
    checkHealth(http.DefaultServeMux)

    if err := http.ListenAndServe(":8080", http.HandlerFunc(handleHTTP)); err != nil {
        log.Fatalf("http.ListenAndServe: %v", err)
    }
}

在应用程序代码中,我希望在 init 函数中定义处理程序,例如:

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, world!")
}

然而,如果我在应用程序代码目录/包中运行 "go build",它会报错说未定义 main 函数:

runtime.main_main: main.main: not defined
runtime.main_main: undefined: main.main

所以我的问题是,我应该如何构建/编译程序,为什么使用标准的 "go build" 命令找不到在 internal 包中定义的 main 函数。

英文:

I'm writing a kind of framework and I would like to make the initialisation of the http server part of this framework. So basically I have a package internal as below which is imported by the framework middleware:

package internal

import(
	"net/http"
	"log"
)

func main() {
	checkHealth(http.DefaultServeMux)

	if err := http.ListenAndServe(":8080", http.HandlerFunc(handleHTTP)); err != nil {
		log.Fatalf("http.ListenAndServe: %v", err)
	}
}

In the app code I'm looking to define the handlers in an init function.
e.g.

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, world!")
}

However if I run go build in the app code directory/package it errors out that the main function is not defined:
runtime.main_main: main.main: not defined
runtime.main_main: undefined: main.main

So my question is how should I build / compile the program so and why using the standard go build command it doesn't find the main function defined in the internal package.

答案1

得分: 4

main 函数必须在 main 包中:程序执行

程序的执行从初始化 main 包开始,然后调用 main 函数。当该函数调用返回时,程序退出。它不会等待其他(非主)goroutine 完成。

如果你想要在启动时初始化某些状态,或者通过简单地导入一个包来产生副作用,你可以使用一个 init 函数。然而,init 函数必须返回,所以你不能在其中使用 http.ListenAndServe 阻塞。

英文:

The main function must be in the main package: Program Execution

> Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

If you want a package to initialize some state at start up, or have side-effects by simply importing it, you use an init function. The init however must return, so you can't block with it http.ListenAndServe.

huangapple
  • 本文由 发表于 2015年3月2日 01:57:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/28797007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定