dongsuoying9059 2019-07-20 14:26
浏览 180
已采纳

Golang从根目录导入包

I'm trying to create a clean architecture API in Go but I'm confused with package logic. Here's the structure of the project.

    main.go                <- package main
    ├── delivery/
    │   ├── endpoints/
    │   │   ├── users.go   <- package endpoints (I want to import ./repository here)
    │   │   └── home.go    <- package endpoints
    │   ├── router.go      <- package delivery
    │   ├── middleware.go  <- package delivery
    ├── repository/
    │   ├── database.go    <- package repository
    │   └── fetchUsers.go  <- package repository

In router.go file I can access and import endpoints like this import "./endpoints", but when I try to import repository package inside users.go or inside home.go I get an error. Is there a way to access repository from files that are in endpoints folder?

  • 写回答

1条回答 默认 最新

  • 普通网友 2019-07-20 14:51
    关注

    The only recommended/canonical way to do imports is with full paths. If your code lives in github.com/Uranus/myproject, then in endpoints/users.go you should import repository thus:

    import "github.com/Uranus/myproject/repository"
    

    Note that it doesn't actually have to be on github. Using modules, you can have any import path you like while developing locally, as long as it's the module name in your go.mod file.

    Follow the examples from this official Go blog post and you'll know what to do.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?