Go项目中的多个主文件

I have a Go project. When I run the program main.go (with function main), it serves a web server serving a JSON object.

In the same folder I have another file serializedata.go (with function main) which writes the JSON object into a file that is served by the web server.

Now, when I try to run go install I get this error:

./serialize_data.go:17: main redeclared in this block previous declaration at ./main.go:13

I want to keep both these files together as they are related. The test data needs to be serialized before it can be served.

How can I prevent to build the serialization.go file?

I'm from python world and there it's easy to have these utils files separately.

Create a file in main package named serialization.go. but change the name of the function main with the any exported function with upper case letter and then call it inside the main.go file. Each package can have only a single main file. So if you want to create a file with main() function inside it declare in another package.

For eg your main.go should looks like.

package main

func main(){
    Serialize()
}

Inside serialization.go file use as

package main

func Serialize(){
   fmt.Println("Serialize")
}

Call above function inside main for serving on web browser

serialize_data.go should put in another folder and then go run serialize_data.go

While not nessarily a good idea, if you avoid go install you can build several executables from the same folder just fine. One of my projects has a tools folder with several executables, that I build using go build. E.g.:

$ ls
Makefile cat.go find.go ls.go
$ cat Makefile
%: %.go
    go build -o $@ $<
$ make ls
go build -o ls ls.go
$ ./ls
Makefile cat.go find.go ls.go