bxcodec / go-clean-arch

Go (Golang) Clean Architecture based on Reading Uncle Bob's Clean Architecture
MIT License
9.06k stars 1.19k forks source link

Need sample to replace Delivery layer #41

Closed programervn closed 3 years ago

programervn commented 4 years ago

Deal all, with clean architecture, it's independence with Delivery layer, in this case, Mr Bxcodec're using echo. Any one have example to replace echo lib/framework with gin-gonic?

mrsufgi commented 4 years ago

I have one that uses the famous httprouter (which is pretty similar to net/http router)

package http

import (
    "fmt"
    "net/http"

    "github.com/julienschmidt/httprouter"
    "github.com/mrsufgi/blanks/domain"
    log "github.com/sirupsen/logrus"
)

var baseRoute string = "/room"

// ResponseError represent the reseponse error struct
type ResponseError struct {
    Message string `json:"message"`
}

//
type RoomHandler struct {
    RService domain.RoomService
}

func createRoute(path string) string {
    return fmt.Sprintf("%s/%s", baseRoute, path)
}

//
func NewRoomHandler(r *httprouter.Router, rs domain.RoomService) *RoomHandler {
    handler := &RoomHandler{
        RService: rs,
    }

    r.POST(baseRoute, handler.create)
    return handler
}

func (h *RoomHandler) create(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    log.Debug("create")

    h.RService.Create()
    w.WriteHeader(200)
}

so if you want to adapt it to use func(c *gin.Context) {} instead. you can just swap the router and the handler. something like:


func NewRoomHandler(r *gin.Engine, rs domain.RoomService) *RoomHandler {

    handler := &RoomHandler{
        RService: rs,
    }

    r.POST("/somePost", handler.posting)
    return handler
}

func (h *RoomHandler) posting(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "pong",
    })
}

not a full example but hope it could help :)