[Go]

[Go] import cycle not allowed - 해결 방안1: interface를 활용한 해결 방안

dogfootman 2024. 6. 18. 02:05

개요

이전 import cycle not allowed 에러를 인터페이스를 활용해 해결

https://dogfootman.com/9

 

[Go] import cycle not allowed - 예제

개요import cycle not allowed가 발생하는 경우+---------------------+ +----------------------+| user 패키지 | | board 패키지 || | | || +-----------------+ | | +------------------+ || | User Struct | | | | Post Struct | || +-----------------+ |

dogfootman.com

 

 

 

 

1. 프로젝트 구조

/dependency2
│
├── main.go
├── user
│   └── user.go
└── board
│   └── board.go
└── interfaces
    └── interfaces.go

 

의존 관계를 없애기 위한 intefaces 패키지를 추가

 

 

 

2. 코드

interfaces.go

package interfaces

type Board interface {
    GetLastPostByUserID(userID int) string
}

type User interface {
    GetUserNameByID(userID int) string
}

 

 

 

board.go

package board

import (
    "dependency2/interfaces"
)

type Post struct {
    ID      int
    UserID  int
    Title   string
    Content string
}

var posts = []*Post{
    {ID: 1, UserID: 1, Title: "First Post", Content: "This is Alice's first post"},
    {ID: 2, UserID: 2, Title: "Hello World", Content: "This is Bob's first post"},
}

type PostInfo struct {
    *Post
    UserName string
}

type Impl struct {
    User interfaces.User
}

func (b *Impl) GetPostList() []*PostInfo {

    var postList []*PostInfo
    for _, post := range posts {
       // 각 게시글 작성자의 이름을 가져옴
       userName := b.User.GetUserNameByID(post.UserID)
       info := &PostInfo{Post: post, UserName: userName}
       postList = append(postList, info)
    }

    return postList
}

func (b *Impl) GetLastPostByUserID(userID int) string {
    for i := len(posts) - 1; i >= 0; i-- {
       if posts[i].UserID == userID {
          return posts[i].Title
       }
    }
    return "No posts found"
}

 

 

 

user.go

package user

import (
    "dependency2/interfaces"
)

type User struct {
    ID        int
    Name      string
    FriendIDs []int
}

var users = []*User{
    {ID: 1, Name: "Alice", FriendIDs: []int{2}},
    {ID: 2, Name: "Bob", FriendIDs: []int{1}},
}

type FriendInfo struct {
    *User
    LastPost string
}

type Impl struct {
    Board interfaces.Board
}

func (u *Impl) GetFriendList(userID int) []*FriendInfo {

    user := u.GetUserByID(userID)
    if user == nil || len(user.FriendIDs) == 0 {
       return nil
    }

    var infoList []*FriendInfo
    for _, friendID := range user.FriendIDs {
       friendUser := u.GetUserByID(friendID)
       // 유저의 마지막 글을 취득
       lastPost := u.Board.GetLastPostByUserID(friendUser.ID)
       info := &FriendInfo{User: friendUser, LastPost: lastPost}
       infoList = append(infoList, info)
    }
    return infoList
}

func (u *Impl) GetUserByID(userID int) *User {
    for _, user := range users {
       if user.ID == userID {
          return user
       }
    }
    return nil
}

func (u *Impl) GetUserNameByID(userID int) string {
    user := u.GetUserByID(userID)
    if user == nil {
       return ""
    }
    return u.GetUserByID(userID).Name
}

 

 

 

main.go

package main

import (
    "dependency2/board"
    "dependency2/user"
    "encoding/json"
    "fmt"
)

func main() {

    boardService := &board.Impl{}
    userService := &user.Impl{}

    boardService.User = userService
    userService.Board = boardService

    friendList := userService.GetFriendList(1)
    friendListJsonData, _ := json.Marshal(friendList)
    fmt.Println("Friend List:", string(friendListJsonData))

    postList := boardService.GetPostList()
    postListJsonData, _ := json.Marshal(postList)
    fmt.Println("Post List:", string(postListJsonData))
}

생성한 서비스를 각각의 서비스의 인터페이스를 통해  주입

  • boardService.User = userService
  • userService.Board = boardService

 

 

 

3. 실행 결과

Friend List: [{"ID":2,"Name":"Bob","FriendIDs":[1],"LastPost":"Hello World"}]
Post List: [{"ID":1,"UserID":1,"Title":"First Post","Content":"This is Alice's first post","UserName":"Alice"},{"ID":2,"UserID":2,"Title":"Hello World","Content":"This is Bob's first post","UserName":"Bob"}]

에러 없이 실행이 가능한 것을 확인