自动生成的代码中的全限定导入路径

My problem

My apologies if the problem is trivial - I'm fairly new to golang, and want to understand the imports mechanism. I use OSX and simple go programs compile and work well.

I've generated a golang server using automatic code generator in the swagger editor. I've unzipped the code into some directory in /tmp/, and the resulting server contains the following main.go file:

package main

import (
        // WARNING!
        // Change this to a fully-qualified import path
        // once you place this file into your project.
        // For example,
        //
        //    sw "github.com/myname/myrepo/go"
        //
        sw "./go"
        "log"
        "net/http"
)

func main() {
        log.Printf("Server started")

        router := sw.NewRouter()

        log.Fatal(http.ListenAndServe(":8080", router))
}

As expected from the comments, go build main.go Fails with the following error:

main.go:11:2:
go/default.go:3:1: expected 'IDENT', found 'import'

Forensics

The directory tree of the project

/tmp/goserver/go-server-server
├── LICENSE
├── api
│   └── swagger.yaml
├── go
│   ├── README.md
│   ├── app.yaml
│   ├── default.go
│   ├── logger.go
│   └── routers.go
└── main.go

go/default.go

package

import (
    "net/http"
)

type Default struct {

}

func QuestionimagePost(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        w.WriteHeader(http.StatusOK)
}

What have I tried

  • Read about go packages
  • Tried to understand the package / import relationship in some github projects
  • Moved the directory tree to $GOPATH/src, and changed the import to sw "sw/go-server-server/go", which still gives main.go:13:2: go/default.go:3:1: expected 'IDENT', found 'import'

What should be the fully-qualified import path of the sw import, and what does it mean?

You need to export some path as the GOPATH, say $HOME/go. export GOPATH=$HOME/go.

Then you can put your project in $GOPATH/src/go-server-server ($HOME/go/src/go-server-server) and your fully qualified path would be go-server-server/go if I am reading everything correctly.

The following did the trick:

  • Adding a package name to all .go files in the go folder (I used blah)

eg. in go/routers.go

package blah

import (
    "log"
    "net/http"
    "time"
)

func Logger(inner http.Handler, name string) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()

        inner.ServeHTTP(w, r)

        log.Printf(
            "%s %s %s %s",
            r.Method,
            r.RequestURI,
            name,
            time.Since(start),
        )
    })
}

Do the same for go/logger.go and, in your case, default.go

  • Following an go/routers.go:7:2: cannot find package "github.com/gorilla/mux" error, go get 'github.com/gorilla/mux'