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.

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

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单