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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化