Why can't I add the main body of my library to golang?

I'm having trouble achieving what should be an easy task. I understand the GitHub model for organizing code (like a library repo and an application repo that consumes a library). I think this is fantastic. But I often find that I want to mylib

come bundled with a simple executable in one file main.go

. main.go

should be package main

and should be imported mylib

. In other words, it should be accurate documentation on how to build an application that consumes this library.

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

I would 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

- package main

, and at startup go install

it generates bin/mylib

and pkg/mylib.a

.

Either main.go

should import "github.com/me/mylib"

(if I do, I get a circular import error), or go

figure out what's going on since this function needs to be inlined and one main.go

in the repo generates an exec. It probably needs to import (and reset the loopback error) is the best way.

Now I have to do

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

      

So I need to import github.com/me/mylib/mylib which is funny.

In sum go install

should resolve the special case of the package and the main one that imports the package and provides a simple cli that demonstrates the packages API. The GitHub model promotes two repositories, but in simple cases, just make a simple clis!

+3


source to share


2 answers


You cannot have multiple packages in a folder. Go works at the package level, not at the file level.

In this case, the convention - the binary that consumes your library - is to create a folder cmd

with the main folder - that is, at https://github.com/bradfitz/camlistore/tree/master/cmd or https://github.com / boltdb / bolt



In your case, it would be:

$GOPATH/src/github.com/me/mylib
    mylib/
      mylib.go
      README.md
      cmd/
        your-lib-tool/
          main.go

      

+6


source


If you just want a handy little wrapper, just a command line interface for your library for demo purpose, and that's ok if the main program isn't built on go get

(not during simple go build

and go install

), but you're fine by running it through go run main.go

or building it manually for example with 6g

: just use the build tag (see http://golang.org/pkg/go/build/#hdr-Build_Constraints ) in main.go:

// +build ignore

      



and you don't need another folder or repo.

+1


source







All Articles