Last active
February 14, 2020 17:11
-
-
Save bylatt/599e8a1c87c2e07d12a6e4058e6d3bd8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/labstack/echo/v4" | |
"net/http" | |
) | |
type Response struct { | |
Data interface{} `json:"data,omitempty"` | |
Status string `json:"status,omitempty"` | |
Message string `json:"message,omitempty"` | |
} | |
type Book struct { | |
Name string `json:"name"` | |
Author string `json:"author"` | |
} | |
type IBookRepo interface { | |
Get(id string) (Book, error) | |
} | |
type BookRepo struct{} | |
func (b BookRepo) Get(id string) (Book, error) { | |
return Book{Name: "Great shit", Author: "Someone on earth"}, nil | |
} | |
type IBookUsecase interface { | |
Get(id string) (Book, error) | |
} | |
type BookUsecase struct { | |
Repo IBookRepo | |
} | |
func (b BookUsecase) Get(id string) (Book, error) { | |
return b.Repo.Get(id) | |
} | |
type IBookHandler interface { | |
Handler(c echo.Context) error | |
} | |
type BookHandler struct { | |
Usecase IBookUsecase | |
} | |
func (b BookHandler) Handler(c echo.Context) error { | |
bookID := c.Param("id") | |
book, err := b.Usecase.Get(bookID) | |
if err != nil { | |
return c.JSON(http.StatusNotFound, &Response{Status: "error", Message: "Book not found"}) | |
} | |
return c.JSON(http.StatusOK, &Response{Data: book, Status: "ok"}) | |
} | |
type Server struct { | |
E *echo.Echo | |
BookHandler IBookHandler | |
} | |
func (s Server) Init() { | |
// Do route register and apply middleware here | |
s.E.GET("/", func(c echo.Context) error { | |
return c.JSON(http.StatusOK, &Response{Status: "ok", Message: "Hello World"}) | |
}) | |
s.E.GET("/books/:id", s.BookHandler.Handler) | |
} | |
func (s Server) Run() { | |
s.E.Logger.Fatal(s.E.Start(":1234")) | |
} | |
func main() { | |
h := BookHandler{Usecase: BookUsecase{Repo: BookRepo{}}} | |
e := echo.New() | |
s := Server{E: e, BookHandler: h} | |
s.Init() | |
s.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment