How to import a package from a subdirectory into Golang?

I am new to Golang and am trying to make api app REST simple work.

Initially, everything was perfect, since I had all the code in the same directory in the package main.

But now I am at the stage when I need to start refactoring the code into subdirectories and packages. Unfortunately, I could not compile the application successfully.

My is GOPATHset to: ~/.workspace Current application:~/.workspace/src/gitlab.com/myapp/api-auth

This is how my current code organization is:

enter image description here

Here is my main.go

package main

import (
    "net/http"
    "os"
    "strings"

    "github.com/gorilla/context"
    "github.com/justinas/alice"
    "gopkg.in/mgo.v2"

    "gitlab.com/myapp/api-auth/middlewares"
)

func main() {
    privateKey := []byte(strings.Replace(os.Getenv("JWT_KEY"), "\\n", "\n", -1))

    conn, err := mgo.Dial(os.Getenv("MONGO_CONN"))

    if err != nil {
        panic(err)
    }

    defer conn.Close()
    conn.SetMode(mgo.Monotonic, true)

    ctx := appContext{
        conn.DB(os.Getenv("MONGO_DB")),
        privateKey,
    }

    err = ctx.db.C("users").EnsureIndex(mgo.Index{
        Key:        []string{"username"},
        Unique:     true,
        Background: true,
        Sparse:     false,
    })

    if err != nil {
        panic(err)
    }

    commonHandlers := alice.New(LoggingHandler, context.ClearHandler, RecoveryHandler, AcceptHandler, ContentTypeHandler)

    router := NewRouter()
    router.Post("/users", commonHandlers.Append(BodyParserHandler(UserResource{})).ThenFunc(ctx.userCreationHandler))
    router.Post("/sessions", commonHandlers.Append(BodyParserHandler(UserResource{})).ThenFunc(ctx.sessionCreationHandler))

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

type appContext struct {
    db         *mgo.Database
    privateKey []byte
}

Here is one of the middleware accept.go(The rest of the middleware is built similarly)

package middlewares

import "net/http"

// AcceptHandler ensures proper accept headers in requests
func AcceptHandler(next http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("Accept") != "application/vnd.api+json" {
            writeError(w, errNotAcceptable)
            return
        }

        next.ServeHTTP(w, r)
    }

    return http.HandlerFunc(fn)
}

This is the error I get when I run go buildfrom the root of my application.

# gitlab.com/utiliti.es/api-auth
./main.go:11: imported and not used: "gitlab.com/myapp/api-auth/middlewares"
./main.go:42: undefined: LoggingHandler
./main.go:42: undefined: RecoveryHandler
./main.go:42: undefined: AcceptHandler
./main.go:42: undefined: ContentTypeHandler
./main.go:45: undefined: BodyParserHandler
./main.go:46: undefined: BodyParserHandler
+4
source share
1 answer

Go

- , . , .

QualifiedIdent = PackageName "." identifier .

, . .

math.Sin  // denotes the Sin function in package math

, , , (§ ) . (PackageName), , ImportPath, .

    ImportDecl       = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
    ImportSpec       = [ "." | PackageName ] ImportPath .
    ImportPath       = string_lit .

. . PackageName , , . (.), , .

ImportPath , .

: ImportPath , , Unicode L, M, N, P S ( ) ! "# $% & '() *,:; <= > ? [] ^` {|} Unicode U + FFFD.

, , , Sin , " lib/math". Sin , .

    Import declaration          Local name of Sin

    import   "lib/math"         math.Sin
    import m "lib/math"         m.Sin
    import . "lib/math"         Sin

. . (), :

    import _ "lib/math"

./main.go:11: imported and not used: "gitlab.com/myapp/api-auth/middlewares"

, middlewares main, .

./main.go:42: undefined: AcceptHandler

, AcceptHandler main, .

" - , . , ".

, main middlewares.AcceptHandler, "gitlab.com/myapp/api-auth/middlewares".

+7

Source: https://habr.com/ru/post/1627582/


All Articles