go - How to properly import a package from sub-directory in Golang? -


i pretty new golang , trying make simple rest api app work.

initially, fine since had code in same directory under main package.

but, @ stage need start refactoring code sub-directories , packages. unfortunately, have not been able compile app successfully.

my gopath set to: ~/.workspace current app at: ~/.workspace/src/gitlab.com/myapp/api-auth

this how current code organization is:

enter image description here

here 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 1 of middleware accept.go (rest of middleware constructed 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 error when run go build root of app.

# gitlab.com/utiliti.es/api-auth ./main.go:11: imported , 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 

i sure missing trivial here. appreciate if please point me right direction here.

the go programming language specification

qualified identifiers

a qualified identifier identifier qualified package name prefix. both package name , identifier must not blank.

qualifiedident = packagename "." identifier . 

a qualified identifier accesses identifier in different package, must imported. identifier must exported , declared in package block of package.

math.sin  // denotes sin function in package math 

import declarations

an import declaration states source file containing declaration depends on functionality of imported package (§program initialization , execution) , enables access exported identifiers of package. import names identifier (packagename) used access , importpath specifies package imported.

    importdecl       = "import" ( importspec | "(" { importspec ";" } ")" ) .     importspec       = [ "." | packagename ] importpath .     importpath       = string_lit . 

the packagename used in qualified identifiers access exported identifiers of package within importing source file. declared in file block. if packagename omitted, defaults identifier specified in package clause of imported package. if explicit period (.) appears instead of name, package's exported identifiers declared in package's package block declared in importing source file's file block , must accessed without qualifier.

the interpretation of importpath implementation-dependent typically substring of full file name of compiled package , may relative repository of installed packages.

implementation restriction: compiler may restrict importpaths non-empty strings using characters belonging unicode's l, m, n, p, , s general categories (the graphic characters without spaces) , may exclude characters !"#$%&'()*,:;<=>?[]^`{|} , unicode replacement character u+fffd.

assume have compiled package containing package clause package math, exports function sin, , installed compiled package in file identified "lib/math". table illustrates how sin accessed in files import package after various types of import declaration.

    import declaration          local name of sin      import   "lib/math"         math.sin     import m "lib/math"         m.sin     import . "lib/math"         sin 

an import declaration declares dependency relation between importing , imported package. illegal package import itself, directly or indirectly, or directly import package without referring of exported identifiers. import package solely side-effects (initialization), use blank identifier explicit package name:

    import _ "lib/math" 

the error

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

says have no uses of package middlewares in package main, true.

the error

./main.go:42: undefined: accepthandler 

says haven't defined accepthandler in package main, true.

"a qualified identifier identifier qualified package name prefix. qualified identifier accesses identifier in different package, must imported."

for example, in package main, use qualified identifier middlewares.accepthandler, use of import "gitlab.com/myapp/api-auth/middlewares".


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

json - Gson().fromJson(jsonResult, Myobject.class) return values in 0's -