Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I add a main to my library in golang?

I'm having trouble achieving what should be an easy task. I understand the GitHub model for code organization (ie a library repo and an app repo that consumes the library). I think it's fantastic. But I find often that I want mylib to come bundled with a simple executable in a single main.go file. The main.go should be package main and should import mylib. In other words, it should be an exact documentation of how to build an app that consumes this library.

My point is, since it is often enough convenient to provide a simple command line interface that wraps your library, there should be an easy way to do this without having to make another repo, and golang should help.

I'd like something like the following:

$GOPATH/src/github.com/me/mylib
    mylib.go
    mylib_also.go
    main.go

where mylib is the library (package mylib) and main.go is package main and on running go install it generates bin/mylib and pkg/mylib.a.

Either main.go should import "github.com/me/mylib" (if I do that now, I get cyclical import error) or go would understand what's happening since this feature should be built in and the one main.go in the repo generates the exec. Probably requiring the import (and dropping the cyclical error) is the better way.

Right now, I have to do

$GOPATH/src/github.com/me/mylib
    mylib/
        mylib.go
    main.go

So I have to import github.com/me/mylib/mylib which is ridiculous.

In sum, go install should allow the special case of a package and a main which imports the package and provides a simple cli that demonstrates the packages API. The GitHub model promotes two repos, but it should be easy to do simple clis in one!

like image 919
Ethan Avatar asked Oct 28 '25 09:10

Ethan


1 Answers

You can't have multiple packages per folder. Go operates on a package-level, not a file level.

Convention in this case—a binary that consumes your library—is to create a cmd folder with your package main - i.e. as per https://github.com/bradfitz/camlistore/tree/master/cmd or https://github.com/boltdb/bolt

In your case this would be:

$GOPATH/src/github.com/me/mylib
    mylib/
      mylib.go
      README.md
      cmd/
        your-lib-tool/
          main.go
like image 128
elithrar Avatar answered Oct 30 '25 07:10

elithrar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!