T
T
tuerxor2017-08-22 14:50:25
go
tuerxor, 2017-08-22 14:50:25

What is the correct way to use imports in Go?

For example, I have a package module, which interacts with different APIs. Accordingly, my hierarchy is something like this:

- module // директория модуля

-- api1 // директория с api1
--- api.go // взаимодействие с api1

-- api2 // директория с api2
--- api.go // взаимодействие с api2

-- api.go // интерфейс для api
-- response.go // структура ответа, который должен вернуть модуль
-- request.go // структура запроса, которой принимает модуль
-- handler.go // принимает запрос, отдает его API, собирает ответ и возвращает общий

Accordingly, the question is, how can I use at least the api.go interface in api1/api.go (or api2/api.go)? For example, I have a method that should return an interface described in api.go, but this method is in api2/api.go, but I cannot return it, because if I do import "../", then, of course, a loop will appear. Tell me what to do in this case? Perhaps I'm not building the structure very correctly, but the logic is simple - there is an interface and there are implementations that implement it, why can't it be referenced in implementations? It is also not clear how to work with the shared object Response, which is also heavily used in api implementations.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
Leonid Nikolaev, 2017-08-22
@tuerxor

in my opinion, it is more correct to make api/ (or common/), move api.go, response.go, etc. there. to have an easy way to access them. at the root, just have a common router.

A
awdemme, 2017-08-22
@awdemme

Clean architecture in a Go application. Part 1

M
mukizu, 2017-08-22
@mukizu

Regarding the structure - you can read different texts on this topic and decide how to act more competently.
> why in implementations it is impossible to refer to it?
Why refer to it there? An interface basically just describes the conditions that something must satisfy.
For example, in api.go you have something like this:

type CommonApi interface {
  Request() error
}

api1.go
import "errors"

type Api struct {}

func (Api) Request() error  {
  return errors.New("Test")
}

And in handler.go something like:
import "<path>/api/v1"

func handle(c CommonApi) error{
  return c.Request()
}

func main()  {
  api := v1.Api{}
  handle(api)
}

Everything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question