Spaces:
Runtime error
Runtime error
Commit ·
483bf6a
1
Parent(s): ab82ffd
Deploy files from GitHub repository
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.exampleAdded+13
- README.md+8-8
- api_spec.txt+117-117
- config/database_config.go+32-27
- config/env_config.go+16-1
- config/jwt_config.go+24-24
- config/supabase.goAdded+15
- controllers/academy_controller.go+228-145
- controllers/upload_controller.goAdded+222
- do_inject_config.ps1+434-434
- do_inject_controllers.ps1+309-309
- do_inject_middleware.ps1+311-311
- do_inject_repository.ps1+326-326
- do_inject_services.ps1+382-382
- go.mod+1
- go.sum+2
- middleware/authentication_middleware.go+48-48
- middleware/authorization_middleware.go+43-43
- middleware/middleware.go+1-1
- models/dto/academy_dto.go+30-30
- models/dto/account_details_dto.go+19-19
- models/dto/event_dto.go+20-20
- models/dto/exam_dto.go+23-23
- models/dto/option_dto.go+12-12
- models/dto/upload_dto.goAdded+43
- models/entity/contant.goAdded+7
- models/entity/entity.go+15
- models/error/error.go+39-15
- provider/config_provider.go+59-38
- provider/controller_provider.go+106-90
- provider/middleware_provider.go+30-30
- provider/provider.go+85-70
- provider/repositories_provider.go+178-170
- provider/services_provider.go+121-103
- provider/storage_interface.goAdded+13
- provider/supabase_storage.goAdded+42
- repositories/academy_repository.go+232-157
- repositories/exam_event_answer_repository.go+59-59
- repositories/exam_event_assign_repository.go+47-47
- repositories/exam_event_attempt_repository.go+55-55
- repositories/exam_event_repository.go+85-85
- repositories/file_repository.goAdded+43
- repositories/problem_set_exam_assign_repository.go+40-40
- repositories/problem_set_repository.go+57-57
- repositories/question_repository.go+55-55
- repositories/result_repository.go+60-60
- router/academy_router.go+44-38
- router/account_detail_router.go+18-18
- router/email_router.go+17-17
- router/event_router.go+19-19
12345678910111213DB_HOST = DB_USER = DB_PASSWORD =DB_PORT =DB_NAME = HOST_ADDRESS = HOST_PORT = SALT = LOG_PATH = logsJWT_SECRET_KEY = s4b3s076SUPABASE_URL=SUPABASE_SERVICE_KEY=SUPABASE_BUCKET_NAME=12345678---title: Quzuu Api Devemoji: 🐠colorFrom: indigocolorTo: graysdk: dockerpinned: false---12345678---title: Quzuu Api Devemoji: 🐠colorFrom: indigocolorTo: graysdk: dockerpinned: false---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118attempt:{id_event:id_exam:remaining_time:answered_question:[]strquestion}question:{id:uuid,question_type:string,content:string,options:[]string,current_answer:[]string,}Answer Soal -> (1) Request ke Backend untuk attempt(2) Rubah UI options(3) Fetch Status -> show Status(4) Set State question.current_answer update(5) Update navigation button soalnya sudah keisi = "hijau", sekarang di nomor berapa = "ungu"# Isian Singkat, Handle onChange =>[kjkajsksaf]Before:def sum(a,b):return {code}print({code})After :def sum(a,b):return <input type = "text" name="answer[0]" />print(<input type = "text" name="answer[1]" />)# Puzzle:#Payload ngirim jawaban (by default) -> Endpoint Ngirim Answeranswer: {id_question:uuid,answers:[]str}#mcanswer: {id_question:uuid,answers:["A"]str}#Complexmc T/Fanswer: {id_question:uuid,answers:[1,0,0,1]}+++++++++++++++#code_Puzzleanswer: {id_question:uuid,answers:["a+b","sum(a,b)"]}# short_answeranswer: {id_question:uuid,answers:["jawaban"]}# upload_fileupload_file -> Form Dataanswer: {id_question:uuid,answers:["{nama_file}"]}#competitive Programmingquestion_type:mock_coding[language]upload_file -> Form Data (Generate nama_file)answer:{id_questions:uuid,answers:["{nama_file}"]}#response answerresponse:{success_response,meta_data{verdict: [AC/WA/TLE/RTE]score:time_exec:memory:}}#Submit{id_attempt:}Attempt{id_user:id_event:id_exam:}# Result / Scoreboard123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118attempt:{id_event:id_exam:remaining_time:answered_question:[]strquestion}question:{id:uuid,question_type:string,content:string,options:[]string,current_answer:[]string,}Answer Soal -> (1) Request ke Backend untuk attempt(2) Rubah UI options(3) Fetch Status -> show Status(4) Set State question.current_answer update(5) Update navigation button soalnya sudah keisi = "hijau", sekarang di nomor berapa = "ungu"# Isian Singkat, Handle onChange =>[kjkajsksaf]Before:def sum(a,b):return {code}print({code})After :def sum(a,b):return <input type = "text" name="answer[0]" />print(<input type = "text" name="answer[1]" />)# Puzzle:#Payload ngirim jawaban (by default) -> Endpoint Ngirim Answeranswer: {id_question:uuid,answers:[]str}#mcanswer: {id_question:uuid,answers:["A"]str}#Complexmc T/Fanswer: {id_question:uuid,answers:[1,0,0,1]}+++++++++++++++#code_Puzzleanswer: {id_question:uuid,answers:["a+b","sum(a,b)"]}# short_answeranswer: {id_question:uuid,answers:["jawaban"]}# upload_fileupload_file -> Form Dataanswer: {id_question:uuid,answers:["{nama_file}"]}#competitive Programmingquestion_type:mock_coding[language]upload_file -> Form Data (Generate nama_file)answer:{id_questions:uuid,answers:["{nama_file}"]}#response answerresponse:{success_response,meta_data{verdict: [AC/WA/TLE/RTE]score:time_exec:memory:}}#Submit{id_attempt:}Attempt{id_user:id_event:id_exam:}# Result / Scoreboard
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051package configimport ("fmt""log""gorm.io/driver/postgres""gorm.io/gorm")type DatabaseConfig interface {AutoMigrateAll(entities ...interface{}) errorGetInstance() *gorm.DB}type databaseConfig struct {db *gorm.DB}func NewDatabaseConfig(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT string) DatabaseConfig {dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Jakarta ",DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT,)db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true,})db = db.Session(&gorm.Session{PrepareStmt: false,})if err != nil {log.Fatal("Failed to connect to database:", err)}return &databaseConfig{db: db}}func (cfg *databaseConfig) AutoMigrateAll(entities ...interface{}) error {// Enable UUID extension firstif err := cfg.db.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"").Error; err != nil {return err}err := cfg.db.AutoMigrate(entities...)return err}func (cfg *databaseConfig) GetInstance() *gorm.DB {return cfg.db}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556package configimport ("fmt""log""gorm.io/driver/postgres""gorm.io/gorm")type DatabaseConfig interface {AutoMigrateAll(entities ...interface{}) errorGetInstance() *gorm.DB}type databaseConfig struct {db *gorm.DB}func NewDatabaseConfig(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT string) DatabaseConfig {dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Jakarta",DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT,)db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true,})if err != nil {log.Fatal("Failed to connect to database:", err)}db = db.Session(&gorm.Session{PrepareStmt: false,})return &databaseConfig{db: db}}func (cfg *databaseConfig) AutoMigrateAll(entities ...interface{}) error {if err := cfg.db.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"").Error; err != nil {log.Printf("Warning: Could not create uuid-ossp extension: %v", err)}// Run migrationserr := cfg.db.AutoMigrate(entities...)if err != nil {return fmt.Errorf("migration failed: %w", err)}return nil}func (cfg *databaseConfig) GetInstance() *gorm.DB {return cfg.db}
17 unmodified lines18192021222355 unmodified lines7980818283848517 unmodified linesGetDatabasePassword() stringGetDatabaseName() stringGetSalt() string}type envConfig struct {55 unmodified linesfunc (e *envConfig) GetSalt() string {salt := os.Getenv("SALT")if salt == "" {return "Def4u|7" // Default salt value}return salt}17 unmodified lines18192021222324252655 unmodified lines82838485868788899091929394959697989910017 unmodified linesGetDatabasePassword() stringGetDatabaseName() stringGetSalt() stringGetSupabaseURL() stringGetSupabaseKey() stringGetSupabaseBucket() string}type envConfig struct {55 unmodified linesfunc (e *envConfig) GetSalt() string {salt := os.Getenv("SALT")if salt == "" {return "Def4u|7"}return salt}func (e *envConfig) GetSupabaseURL() string {return os.Getenv("SUPABASE_URL")}func (e *envConfig) GetSupabaseKey() string {return os.Getenv("SUPABASE_SERVICE_KEY")}func (e *envConfig) GetSupabaseBucket() string {return os.Getenv("SUPABASE_BUCKET_NAME")}
123456789101112131415161718192021222324package configtype JWTConfig interface {SetSecretKey(key string)GetSecretKey() string}type jwtConfig struct {secretKey string}func NewJWTConfig(secretKey string) JWTConfig {return &jwtConfig{secretKey: secretKey,}}func (cfg *jwtConfig) SetSecretKey(key string) {cfg.secretKey = key}func (cfg *jwtConfig) GetSecretKey() string {return cfg.secretKey}123456789101112131415161718192021222324package configtype JWTConfig interface {SetSecretKey(key string)GetSecretKey() string}type jwtConfig struct {secretKey string}func NewJWTConfig(secretKey string) JWTConfig {return &jwtConfig{secretKey: secretKey,}}func (cfg *jwtConfig) SetSecretKey(key string) {cfg.secretKey = key}func (cfg *jwtConfig) GetSecretKey() string {return cfg.secretKey}
123456789101112131415package config
type SupabaseConfig struct { URL string ServiceKey string BucketName string}
func NewSupabaseConfig(url, key, bucket string) SupabaseConfig { return SupabaseConfig{ URL: url, ServiceKey: key, BucketName: bucket, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145package controllersimport ("fmt""net/http""strconv""abdanhafidz.com/go-boilerplate/models/dto""abdanhafidz.com/go-boilerplate/services""github.com/gin-gonic/gin""github.com/google/uuid")type AcademyController interface {CreateAcademy(ctx *gin.Context)GetAcademy(ctx *gin.Context)GetAcademyDetail(ctx *gin.Context)ListAcademies(ctx *gin.Context)UpdateAcademy(ctx *gin.Context)DeleteAcademy(ctx *gin.Context)GetMaterial(ctx *gin.Context)CreateMaterial(ctx *gin.Context)CreateContent(ctx *gin.Context)GetContent(ctx *gin.Context)UpdateContentProgress(ctx *gin.Context)}type academyController struct {academyService services.AcademyService}func NewAcademyController(academyService services.AcademyService) AcademyController {return &academyController{academyService}}func (c *academyController) GetAcademy(ctx *gin.Context) {academySlug := ctx.Param("academy_slug")accountId,_ := uuid.Parse(ctx.Value("account_id").(string))res, err := c.academyService.GetAcademy(ctx.Request.Context(), accountId, academySlug)ResponseJSON(ctx, gin.H{"academy_slug": academySlug}, res, err)}func (c *academyController) GetAcademyDetail(ctx *gin.Context) {id, _ := uuid.Parse(ctx.Param("id"))res, err := c.academyService.GetAcademyDetail(ctx.Request.Context(), id)ResponseJSON(ctx, gin.H{"id": id}, res, err)}func (c *academyController) ListAcademies(ctx *gin.Context) {accountId,_ := uuid.Parse(ctx.Value("account_id").(string))fmt.Println("Account ID in ListAcademies:", accountId)res, err := c.academyService.ListAcademies(ctx.Request.Context(), accountId)ResponseJSON(ctx, gin.H{}, res, err)}func (c *academyController) CreateAcademy(ctx *gin.Context) {req := RequestJSON[dto.CreateAcademyRequest](ctx)res, err := c.academyService.CreateAcademy(ctx.Request.Context(), req)ResponseJSON(ctx, req, res, err)}func (c *academyController) UpdateAcademy(ctx *gin.Context) {id, _ := uuid.Parse(ctx.Param("id"))req := RequestJSON[dto.UpdateAcademyRequest](ctx)res, err := c.academyService.UpdateAcademy(ctx.Request.Context(), id, req)ResponseJSON(ctx, req, res, err)}func (c *academyController) DeleteAcademy(ctx *gin.Context) {id, _ := uuid.Parse(ctx.Param("id"))err := c.academyService.DeleteAcademy(ctx.Request.Context(), id)ResponseJSON(ctx, gin.H{"id": id}, gin.H{"deleted": true}, err)}// MATERIALfunc (c *academyController) GetMaterial(ctx *gin.Context) {academySlug := ctx.Param("academy_slug")materialSlug := ctx.Param("material_slug")accountId,_ := uuid.Parse(ctx.Value("account_id").(string))res, err := c.academyService.GetMaterial(ctx.Request.Context(), accountId, academySlug, materialSlug)ResponseJSON(ctx, gin.H{"academy_slug": academySlug, "material_slug": materialSlug}, res, err)}func (c *academyController) CreateMaterial(ctx *gin.Context) {req := RequestJSON[dto.CreateMaterialRequest](ctx)res, err := c.academyService.CreateMaterial(ctx.Request.Context(), req)ResponseJSON(ctx, req, res, err)}// CONTENTfunc (c *academyController) GetContent(ctx *gin.Context) {accountId,_ := uuid.Parse(ctx.Value("account_id").(string))academySlug := ctx.Param("academy_slug")materialSlug := ctx.Param("material_slug")orderString := ctx.Param("order")orderID64, err := strconv.ParseUint(orderString, 10, 64)if err != nil {ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid 'order' parameter. Must be a positive integer."})return}order := uint(orderID64)res, err := c.academyService.GetContent(ctx.Request.Context(),accountId, academySlug, materialSlug, order)ResponseJSON(ctx, gin.H{"academy_slug": academySlug, "material_slug": materialSlug, "content_slug": order}, res, err)}func (c *academyController) CreateContent(ctx *gin.Context) {req := RequestJSON[dto.CreateContentRequest](ctx)res, err := c.academyService.CreateContent(ctx.Request.Context(), req)ResponseJSON(ctx, req, res, err)}func (c *academyController) UpdateContentProgress(ctx *gin.Context) {accountId,_ := uuid.Parse(ctx.Value("account_id").(string))academySlug := ctx.Param("academy_slug")materialSlug := ctx.Param("material_slug")orderString := ctx.Param("order")orderID64, err := strconv.ParseUint(orderString, 10, 64)if err != nil {ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid 'order' parameter. Must be a positive integer."})return}order := uint(orderID64)contentProgress, materialProgress, academyProgress, err := c.academyService.UpdateContentProgress(ctx, accountId, academySlug, materialSlug, order)res := gin.H{"content_progress": contentProgress,"material_progress": materialProgress,"academy_progress": academyProgress,}ResponseJSON(ctx, gin.H{"academy_slug": academySlug, "material_slug": materialSlug, "content_slug": order}, res, err)}//! TODO: MAKE FULL CRUD FOR ADMIN USER123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228package controllersimport ("fmt""net/http""strconv""abdanhafidz.com/go-boilerplate/models/dto"http_error "abdanhafidz.com/go-boilerplate/models/error""abdanhafidz.com/go-boilerplate/services""github.com/gin-gonic/gin""github.com/google/uuid")type AcademyController interface {// AcademyCreateAcademy(ctx *gin.Context)GetAcademy(ctx *gin.Context)GetAcademyDetail(ctx *gin.Context)ListAcademies(ctx *gin.Context)UpdateAcademy(ctx *gin.Context)DeleteAcademy(ctx *gin.Context)// MaterialGetMaterial(ctx *gin.Context)CreateMaterial(ctx *gin.Context)DeleteMaterial(ctx *gin.Context)// ContentCreateContent(ctx *gin.Context)GetContent(ctx *gin.Context)DeleteContent(ctx *gin.Context)// ProgressUpdateContentProgress(ctx *gin.Context)}type academyController struct {academyService services.AcademyService}func NewAcademyController(academyService services.AcademyService) AcademyController {return &academyController{academyService}}// ================= ACADEMY =================func (c *academyController) GetAcademy(ctx *gin.Context) {academySlug := ctx.Param("academy_slug")accountIdStr := ctx.GetString("account_id")accountId, err := uuid.Parse(accountIdStr)if err != nil {// [FIX] Tambahkan [any, any] agar compiler tau tipenyaResponseJSON[any, any](ctx, nil, nil, http_error.UNAUTHORIZED)return}res, err := c.academyService.GetAcademy(ctx.Request.Context(), accountId, academySlug)ResponseJSON(ctx, gin.H{"academy_slug": academySlug}, res, err)}func (c *academyController) GetAcademyDetail(ctx *gin.Context) {id, err := uuid.Parse(ctx.Param("id"))if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.BAD_REQUEST_ERROR)return}res, err := c.academyService.GetAcademyDetail(ctx.Request.Context(), id)ResponseJSON(ctx, gin.H{"id": id}, res, err)}func (c *academyController) ListAcademies(ctx *gin.Context) {accountIdStr := ctx.GetString("account_id")accountId, err := uuid.Parse(accountIdStr)if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.UNAUTHORIZED)return}fmt.Println("Account ID in ListAcademies:", accountId)res, err := c.academyService.ListAcademies(ctx.Request.Context(), accountId)ResponseJSON(ctx, gin.H{}, res, err)}func (c *academyController) CreateAcademy(ctx *gin.Context) {req := RequestJSON[dto.CreateAcademyRequest](ctx)res, err := c.academyService.CreateAcademy(ctx.Request.Context(), req)ResponseJSON(ctx, req, res, err)}func (c *academyController) UpdateAcademy(ctx *gin.Context) {id, err := uuid.Parse(ctx.Param("id"))if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.BAD_REQUEST_ERROR)return}req := RequestJSON[dto.UpdateAcademyRequest](ctx)res, err := c.academyService.UpdateAcademy(ctx.Request.Context(), id, req)ResponseJSON(ctx, req, res, err)}func (c *academyController) DeleteAcademy(ctx *gin.Context) {id, err := uuid.Parse(ctx.Param("id"))if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.BAD_REQUEST_ERROR)return}err = c.academyService.DeleteAcademy(ctx.Request.Context(), id)ResponseJSON(ctx, gin.H{"id": id}, gin.H{"deleted": true}, err)}// ================= MATERIAL =================func (c *academyController) GetMaterial(ctx *gin.Context) {academySlug := ctx.Param("academy_slug")materialSlug := ctx.Param("material_slug")accountIdStr := ctx.GetString("account_id")accountId, err := uuid.Parse(accountIdStr)if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.UNAUTHORIZED)return}res, err := c.academyService.GetMaterial(ctx.Request.Context(), accountId, academySlug, materialSlug)ResponseJSON(ctx, gin.H{"academy_slug": academySlug, "material_slug": materialSlug}, res, err)}func (c *academyController) CreateMaterial(ctx *gin.Context) {req := RequestJSON[dto.CreateMaterialRequest](ctx)res, err := c.academyService.CreateMaterial(ctx.Request.Context(), req)ResponseJSON(ctx, req, res, err)}func (c *academyController) DeleteMaterial(ctx *gin.Context) {id, err := uuid.Parse(ctx.Param("id"))if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.BAD_REQUEST_ERROR)return}err = c.academyService.DeleteMaterial(ctx.Request.Context(), id)ResponseJSON(ctx, gin.H{"id": id}, gin.H{"deleted": true}, err)}// ================= CONTENT =================func (c *academyController) GetContent(ctx *gin.Context) {accountIdStr := ctx.GetString("account_id")accountId, err := uuid.Parse(accountIdStr)if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.UNAUTHORIZED)return}academySlug := ctx.Param("academy_slug")materialSlug := ctx.Param("material_slug")orderID64, err := strconv.ParseUint(ctx.Param("order"), 10, 64)if err != nil {ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid 'order' parameter. Must be a positive integer."})return}order := uint(orderID64)res, err := c.academyService.GetContent(ctx.Request.Context(), accountId, academySlug, materialSlug, order)ResponseJSON(ctx, gin.H{"academy_slug": academySlug, "material_slug": materialSlug, "content_order": order}, res, err)}func (c *academyController) CreateContent(ctx *gin.Context) {req := RequestJSON[dto.CreateContentRequest](ctx)res, err := c.academyService.CreateContent(ctx.Request.Context(), req)ResponseJSON(ctx, req, res, err)}func (c *academyController) DeleteContent(ctx *gin.Context) {id, err := uuid.Parse(ctx.Param("id"))if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.BAD_REQUEST_ERROR)return}err = c.academyService.DeleteContent(ctx.Request.Context(), id)ResponseJSON(ctx, gin.H{"id": id}, gin.H{"deleted": true}, err)}// ================= PROGRESS =================func (c *academyController) UpdateContentProgress(ctx *gin.Context) {accountIdStr := ctx.GetString("account_id")accountId, err := uuid.Parse(accountIdStr)if err != nil {// [FIX] Tambahkan [any, any]ResponseJSON[any, any](ctx, nil, nil, http_error.UNAUTHORIZED)return}academySlug := ctx.Param("academy_slug")materialSlug := ctx.Param("material_slug")orderID64, err := strconv.ParseUint(ctx.Param("order"), 10, 64)if err != nil {ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid 'order' parameter. Must be a positive integer."})return}order := uint(orderID64)contentProgress, materialProgress, academyProgress, err := c.academyService.UpdateContentProgress(ctx.Request.Context(), accountId, academySlug, materialSlug, order)res := gin.H{"content_progress": contentProgress,"material_progress": materialProgress,"academy_progress": academyProgress,}ResponseJSON(ctx, gin.H{"academy_slug": academySlug, "material_slug": materialSlug, "content_order": order}, res, err)}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222package controllers
import ( "errors" "net/http" "path/filepath" "strings"
"github.com/gin-gonic/gin" "github.com/google/uuid"
"abdanhafidz.com/go-boilerplate/models/dto" http_error "abdanhafidz.com/go-boilerplate/models/error" "abdanhafidz.com/go-boilerplate/services")
type UploadController struct { uploadService *services.UploadService}
func NewUploadController(s *services.UploadService) *UploadController { return &UploadController{uploadService: s}}
func (c *UploadController) Upload(ctx *gin.Context) { // 1. Parse Multipart Form (Limit 32MB) if err := ctx.Request.ParseMultipartForm(32 << 20); err != nil { if strings.Contains(err.Error(), "http: request body too large") { ctx.JSON(http.StatusBadRequest, gin.H{ "status": "error", "message": "File size exceeds the allowed limit of 32MB", }) return } ctx.JSON(http.StatusBadRequest, gin.H{ "status": "error", "code": "INVALID_FORM", "message": "Failed to parse form data", }) return }
form, err := ctx.MultipartForm() if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{ "status": "error", "code": "INVALID_DATA", "message": "Invalid form data", }) return }
files := form.File["files"] if len(files) == 0 { ctx.JSON(http.StatusBadRequest, gin.H{ "status": "error", "message": "No files uploaded", }) return }
// 2. Determine Upload Context uploadContext := ctx.PostForm("context") if uploadContext == "" { // Auto-infer context based on first file extension if not provided ext := strings.ToLower(filepath.Ext(files[0].Filename)) uploadContext = c.inferContextFromExt(ext) }
// 3. Get Account ID from Context (Middleware) accountIDStr := ctx.GetString("account_id") if accountIDStr == "" { ctx.JSON(http.StatusUnauthorized, gin.H{ "status": "error", "message": "Unauthorized: Missing account ID", }) return }
accountID, err := uuid.Parse(accountIDStr) if err != nil { ctx.JSON(http.StatusUnauthorized, gin.H{ "status": "error", "message": "Unauthorized: Invalid UUID format", }) return }
// 4. Call Service uploadedFiles, err := c.uploadService.UploadFiles(ctx, files, uploadContext, accountID) if err != nil { // Map Service Errors to HTTP Status if errors.Is(err, http_error.FILE_TOO_LARGE) || errors.Is(err, http_error.INVALID_FILE_TYPE) || errors.Is(err, http_error.BAD_REQUEST_ERROR) { ctx.JSON(http.StatusBadRequest, gin.H{ "status": "error", "message": err.Error(), }) return }
if errors.Is(err, http_error.PARTIAL_UPLOAD_FAILURE) { ctx.JSON(http.StatusUnprocessableEntity, gin.H{ "status": "error", "message": err.Error(), // Opsional: Anda bisa mengembalikan file yang berhasil di sini jika perlu }) return }
ctx.JSON(http.StatusInternalServerError, gin.H{ "status": "error", "message": err.Error(), }) return }
// 5. Prepare Response DTO var fileResponses []dto.FileResponse for _, f := range uploadedFiles { fileResponses = append(fileResponses, dto.FileResponse{ Id: f.Id, OriginalName: f.OriginalName, URL: f.Path, MimeType: f.MimeType, Size: f.Size, CreatedAt: f.CreatedAt, }) }
ctx.JSON(http.StatusCreated, dto.FileUploadResponse{ Status: "success", Message: "Files uploaded successfully", Data: fileResponses, })}
func (c *UploadController) GetFileByID(ctx *gin.Context) { // 1. Validate Param ID fileIDStr := ctx.Param("id") fileID, err := uuid.Parse(fileIDStr) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{ "status": "error", "message": "Invalid file ID format", }) return }
// 2. Validate Account ID accountIDStr := ctx.GetString("account_id") if accountIDStr == "" { ctx.JSON(http.StatusUnauthorized, gin.H{ "status": "error", "message": "Unauthorized: Missing account ID", }) return }
accountID, err := uuid.Parse(accountIDStr) if err != nil { ctx.JSON(http.StatusUnauthorized, gin.H{ "status": "error", "message": "Unauthorized: Invalid UUID format", }) return }
// 3. Call Service fileData, err := c.uploadService.GetFileByID(ctx, fileID, accountID) if err != nil { if errors.Is(err, http_error.NOT_FOUND_ERROR) { ctx.JSON(http.StatusNotFound, gin.H{ "status": "error", "message": "File not found or access denied", }) return }
ctx.JSON(http.StatusInternalServerError, gin.H{ "status": "error", "message": err.Error(), }) return }
// 4. Response response := dto.FileResponse{ Id: fileData.Id, OriginalName: fileData.OriginalName, URL: fileData.Path, MimeType: fileData.MimeType, Size: fileData.Size, CreatedAt: fileData.CreatedAt, }
ctx.JSON(http.StatusOK, dto.FileResponseSingle{ Status: "success", Message: "File retrieved successfully", Data: response, })}
// Helper untuk logika inferensi context (clean code)func (c *UploadController) inferContextFromExt(ext string) string { isSourceCode := map[string]bool{ ".cpp": true, ".c": true, ".py": true, ".java": true, ".go": true, ".js": true, ".txt": true, } isDocument := map[string]bool{ ".pdf": true, }
if isSourceCode[ext] { return "submission" } if isDocument[ext] { return "material" } return "general"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Configuration.DESCRIPTIONScans ./config/ directory, discovers all config constructors, infers their dependencies,and generates provider/config_provider.go with full DI wiring. Special handling forchained dependencies where configs depend on other configs (e.g., DatabaseConfig depends on EnvConfig)..EXAMPLE.\config_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Handles config-to-config dependencies with topological sorting- Special handling for method calls like envConfig.GetDatabaseHost()#>[CmdletBinding()]param()# Configuration$ConfigDir = "./config"$OutputFile = "provider/config_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/config"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass ConfigInfo {[string]$ConstructorName # NewDatabaseConfig[string]$Domain # DatabaseConfig[string]$VarName # databaseConfig[System.Collections.Generic.List[Parameter]]$Parameters[System.Collections.Generic.List[string]]$ConfigDependenciesConfigInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()$this.ConfigDependencies = [System.Collections.Generic.List[string]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for config constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$configs = [System.Collections.Generic.List[ConfigInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxConfig(...) XxxConfig$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Config)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Config)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxConfig)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$config = [ConfigInfo]::new()$config.ConstructorName = $constructorName$config.Domain = $domain$config.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($config.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$config.Parameters.Add($p)# Track config dependencies (configs that depend on other configs)if ($p.NormalizedType -match 'Config$') {$config.ConfigDependencies.Add($p.NormalizedType)}}}$configs.Add($config)Write-ColorOutput " Found: $constructorName" "Green"}}if ($configs.Count -eq 0) {Write-ColorOutput "No config constructors found matching pattern 'NewXxxConfig'!" "Red"exit 1}Write-ColorOutput "`nTotal configs discovered: $($configs.Count)" "Blue"return $configs}function Get-TopologicalOrder {param([System.Collections.Generic.List[ConfigInfo]]$Configs)Write-ColorOutput "`nBuilding dependency graph..." "Cyan"# Build adjacency list$graph = @{}$inDegree = @{}$domainToConfig = @{}foreach ($cfg in $Configs) {$graph[$cfg.Domain] = [System.Collections.Generic.List[string]]::new()$inDegree[$cfg.Domain] = 0$domainToConfig[$cfg.Domain] = $cfg}# Build edges (dependencies)foreach ($cfg in $Configs) {foreach ($dep in $cfg.ConfigDependencies) {if ($graph.ContainsKey($dep)) {$graph[$dep].Add($cfg.Domain)$inDegree[$cfg.Domain]++}}}# Kahn's algorithm for topological sort$queue = [System.Collections.Generic.Queue[string]]::new()foreach ($domain in $inDegree.Keys) {if ($inDegree[$domain] -eq 0) {$queue.Enqueue($domain)}}$sorted = [System.Collections.Generic.List[string]]::new()while ($queue.Count -gt 0) {$current = $queue.Dequeue()$sorted.Add($current)foreach ($neighbor in $graph[$current]) {$inDegree[$neighbor]--if ($inDegree[$neighbor] -eq 0) {$queue.Enqueue($neighbor)}}}# Check for cyclesif ($sorted.Count -ne $Configs.Count) {$remaining = $inDegree.Keys | Where-Object { $inDegree[$_] -gt 0 }Write-ColorOutput "`nERROR: Circular dependency detected in configs!" "Red"Write-ColorOutput "Configs involved in cycle: $($remaining -join ', ')" "Yellow"exit 1}Write-ColorOutput " Dependency graph validated (no cycles)" "Green"Write-ColorOutput " Topological order: $($sorted -join ' -> ')" "Blue"# Return configs in topological orderreturn $sorted | ForEach-Object { $domainToConfig[$_] }}function Resolve-ConfigArgument {param([Parameter]$Param,[string]$DependentConfigVar)$type = $Param.NormalizedType$paramName = $Param.Name# SPECIAL CASE MAPPINGS FOR CONFIG# ============================================# 1. Config pattern: XxxConfig -> already instantiated config variableif ($type -match '^(.+)Config$') {$configVarName = Get-LowerCamelCase $typereturn $configVarName}# 2. String parameters - try to infer from parameter name and match with config getter methodsif ($type -eq "string") {# Common patterns for EnvConfig getters$getterMappings = @{"host" = "GetDatabaseHost()""databaseHost" = "GetDatabaseHost()""user" = "GetDatabaseUser()""databaseUser" = "GetDatabaseUser()""password" = "GetDatabasePassword()""databasePassword" = "GetDatabasePassword()""name" = "GetDatabaseName()""databaseName" = "GetDatabaseName()""dbName" = "GetDatabaseName()""port" = "GetDatabasePort()""databasePort" = "GetDatabasePort()""salt" = "GetSalt()""secret" = "GetSecretKey()""secretKey" = "GetSecretKey()""jwtSecret" = "GetSecretKey()""apiKey" = "GetAPIKey()""timezone" = "GetTimezone()"}# Try to find matching getterforeach ($key in $getterMappings.Keys) {if ($paramName -like "*$key*") {return "envConfig.$($getterMappings[$key])"}}# If dependent on a config, try to construct getter name from param nameif ($DependentConfigVar) {# Convert paramName to PascalCase for getter$getterName = (Get-Culture).TextInfo.ToTitleCase($paramName)$getterName = $getterName -replace '\s', ''return "${DependentConfigVar}.Get${getterName}()"}}# 3. Int/port parametersif ($type -eq "int" -or $type -eq "int32" -or $type -eq "int64") {if ($paramName -match "port") {return "envConfig.GetDatabasePort()"}}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Redis config# if ($paramName -match "redis") {# return "envConfig.GetRedisURL()"# }## Example: Mail config# if ($paramName -match "smtp") {# return "envConfig.GetSMTPHost()"# }# --------------------------------------------# 4. Hardcoded constants (timezone example)if ($type -eq "string" -and $paramName -match "timezone|location") {return "`"Asia/Jakarta`""}# 5. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) for $paramName */"}function Generate-ProviderCode {param([System.Collections.Generic.List[ConfigInfo]]$ConfigsInOrder)Write-ColorOutput "`nGenerating config provider code..." "Cyan"$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type ConfigProvider interface {")foreach ($cfg in $ConfigsInOrder) {$line = "`tProvide$($cfg.Domain)() config.$($cfg.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type configProvider struct {")foreach ($cfg in $ConfigsInOrder) {$line = "`t$($cfg.VarName) config.$($cfg.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewConfigProvider() ConfigProvider {")# Initialize configs in topological orderforeach ($cfg in $ConfigsInOrder) {# Check if this config depends on another config$dependentConfigVar = $nullif ($cfg.ConfigDependencies.Count -gt 0) {$dependentConfigVar = Get-LowerCamelCase $cfg.ConfigDependencies[0]}$args = @()foreach ($param in $cfg.Parameters) {$args += Resolve-ConfigArgument -Param $param -DependentConfigVar $dependentConfigVar}$argsStr = $args -join ", "$line = "`t$($cfg.VarName) := config.$($cfg.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`treturn &configProvider{")foreach ($cfg in $ConfigsInOrder) {$line = "`t`t$($cfg.VarName): $($cfg.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($cfg in $ConfigsInOrder) {[void]$sb.AppendLine("func (c *configProvider) Provide$($cfg.Domain)() config.$($cfg.Domain) {")[void]$sb.AppendLine("`treturn c.$($cfg.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Config Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all config constructors$configs = Parse-GoFiles -Directory $ConfigDir# Step 2: Perform topological sort (configs can depend on other configs)$sortedConfigs = Get-TopologicalOrder -Configs $configs# Step 3: Generate provider code$code = Generate-ProviderCode -ConfigsInOrder $sortedConfigs# Step 4: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Config provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Configuration.DESCRIPTIONScans ./config/ directory, discovers all config constructors, infers their dependencies,and generates provider/config_provider.go with full DI wiring. Special handling forchained dependencies where configs depend on other configs (e.g., DatabaseConfig depends on EnvConfig)..EXAMPLE.\config_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Handles config-to-config dependencies with topological sorting- Special handling for method calls like envConfig.GetDatabaseHost()#>[CmdletBinding()]param()# Configuration$ConfigDir = "./config"$OutputFile = "provider/config_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/config"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass ConfigInfo {[string]$ConstructorName # NewDatabaseConfig[string]$Domain # DatabaseConfig[string]$VarName # databaseConfig[System.Collections.Generic.List[Parameter]]$Parameters[System.Collections.Generic.List[string]]$ConfigDependenciesConfigInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()$this.ConfigDependencies = [System.Collections.Generic.List[string]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for config constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$configs = [System.Collections.Generic.List[ConfigInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxConfig(...) XxxConfig$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Config)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Config)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxConfig)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$config = [ConfigInfo]::new()$config.ConstructorName = $constructorName$config.Domain = $domain$config.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($config.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$config.Parameters.Add($p)# Track config dependencies (configs that depend on other configs)if ($p.NormalizedType -match 'Config$') {$config.ConfigDependencies.Add($p.NormalizedType)}}}$configs.Add($config)Write-ColorOutput " Found: $constructorName" "Green"}}if ($configs.Count -eq 0) {Write-ColorOutput "No config constructors found matching pattern 'NewXxxConfig'!" "Red"exit 1}Write-ColorOutput "`nTotal configs discovered: $($configs.Count)" "Blue"return $configs}function Get-TopologicalOrder {param([System.Collections.Generic.List[ConfigInfo]]$Configs)Write-ColorOutput "`nBuilding dependency graph..." "Cyan"# Build adjacency list$graph = @{}$inDegree = @{}$domainToConfig = @{}foreach ($cfg in $Configs) {$graph[$cfg.Domain] = [System.Collections.Generic.List[string]]::new()$inDegree[$cfg.Domain] = 0$domainToConfig[$cfg.Domain] = $cfg}# Build edges (dependencies)foreach ($cfg in $Configs) {foreach ($dep in $cfg.ConfigDependencies) {if ($graph.ContainsKey($dep)) {$graph[$dep].Add($cfg.Domain)$inDegree[$cfg.Domain]++}}}# Kahn's algorithm for topological sort$queue = [System.Collections.Generic.Queue[string]]::new()foreach ($domain in $inDegree.Keys) {if ($inDegree[$domain] -eq 0) {$queue.Enqueue($domain)}}$sorted = [System.Collections.Generic.List[string]]::new()while ($queue.Count -gt 0) {$current = $queue.Dequeue()$sorted.Add($current)foreach ($neighbor in $graph[$current]) {$inDegree[$neighbor]--if ($inDegree[$neighbor] -eq 0) {$queue.Enqueue($neighbor)}}}# Check for cyclesif ($sorted.Count -ne $Configs.Count) {$remaining = $inDegree.Keys | Where-Object { $inDegree[$_] -gt 0 }Write-ColorOutput "`nERROR: Circular dependency detected in configs!" "Red"Write-ColorOutput "Configs involved in cycle: $($remaining -join ', ')" "Yellow"exit 1}Write-ColorOutput " Dependency graph validated (no cycles)" "Green"Write-ColorOutput " Topological order: $($sorted -join ' -> ')" "Blue"# Return configs in topological orderreturn $sorted | ForEach-Object { $domainToConfig[$_] }}function Resolve-ConfigArgument {param([Parameter]$Param,[string]$DependentConfigVar)$type = $Param.NormalizedType$paramName = $Param.Name# SPECIAL CASE MAPPINGS FOR CONFIG# ============================================# 1. Config pattern: XxxConfig -> already instantiated config variableif ($type -match '^(.+)Config$') {$configVarName = Get-LowerCamelCase $typereturn $configVarName}# 2. String parameters - try to infer from parameter name and match with config getter methodsif ($type -eq "string") {# Common patterns for EnvConfig getters$getterMappings = @{"host" = "GetDatabaseHost()""databaseHost" = "GetDatabaseHost()""user" = "GetDatabaseUser()""databaseUser" = "GetDatabaseUser()""password" = "GetDatabasePassword()""databasePassword" = "GetDatabasePassword()""name" = "GetDatabaseName()""databaseName" = "GetDatabaseName()""dbName" = "GetDatabaseName()""port" = "GetDatabasePort()""databasePort" = "GetDatabasePort()""salt" = "GetSalt()""secret" = "GetSecretKey()""secretKey" = "GetSecretKey()""jwtSecret" = "GetSecretKey()""apiKey" = "GetAPIKey()""timezone" = "GetTimezone()"}# Try to find matching getterforeach ($key in $getterMappings.Keys) {if ($paramName -like "*$key*") {return "envConfig.$($getterMappings[$key])"}}# If dependent on a config, try to construct getter name from param nameif ($DependentConfigVar) {# Convert paramName to PascalCase for getter$getterName = (Get-Culture).TextInfo.ToTitleCase($paramName)$getterName = $getterName -replace '\s', ''return "${DependentConfigVar}.Get${getterName}()"}}# 3. Int/port parametersif ($type -eq "int" -or $type -eq "int32" -or $type -eq "int64") {if ($paramName -match "port") {return "envConfig.GetDatabasePort()"}}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Redis config# if ($paramName -match "redis") {# return "envConfig.GetRedisURL()"# }## Example: Mail config# if ($paramName -match "smtp") {# return "envConfig.GetSMTPHost()"# }# --------------------------------------------# 4. Hardcoded constants (timezone example)if ($type -eq "string" -and $paramName -match "timezone|location") {return "`"Asia/Jakarta`""}# 5. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) for $paramName */"}function Generate-ProviderCode {param([System.Collections.Generic.List[ConfigInfo]]$ConfigsInOrder)Write-ColorOutput "`nGenerating config provider code..." "Cyan"$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type ConfigProvider interface {")foreach ($cfg in $ConfigsInOrder) {$line = "`tProvide$($cfg.Domain)() config.$($cfg.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type configProvider struct {")foreach ($cfg in $ConfigsInOrder) {$line = "`t$($cfg.VarName) config.$($cfg.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewConfigProvider() ConfigProvider {")# Initialize configs in topological orderforeach ($cfg in $ConfigsInOrder) {# Check if this config depends on another config$dependentConfigVar = $nullif ($cfg.ConfigDependencies.Count -gt 0) {$dependentConfigVar = Get-LowerCamelCase $cfg.ConfigDependencies[0]}$args = @()foreach ($param in $cfg.Parameters) {$args += Resolve-ConfigArgument -Param $param -DependentConfigVar $dependentConfigVar}$argsStr = $args -join ", "$line = "`t$($cfg.VarName) := config.$($cfg.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`treturn &configProvider{")foreach ($cfg in $ConfigsInOrder) {$line = "`t`t$($cfg.VarName): $($cfg.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($cfg in $ConfigsInOrder) {[void]$sb.AppendLine("func (c *configProvider) Provide$($cfg.Domain)() config.$($cfg.Domain) {")[void]$sb.AppendLine("`treturn c.$($cfg.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Config Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all config constructors$configs = Parse-GoFiles -Directory $ConfigDir# Step 2: Perform topological sort (configs can depend on other configs)$sortedConfigs = Get-TopologicalOrder -Configs $configs# Step 3: Generate provider code$code = Generate-ProviderCode -ConfigsInOrder $sortedConfigs# Step 4: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Config provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Controllers.DESCRIPTIONScans ./controllers/ directory, discovers all controller constructors, infers their dependencies,and generates provider/controller_provider.go with full DI wiring..EXAMPLE.\controller_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Controllers depend on services from ServicesProvider#>[CmdletBinding()]param()# Configuration$ControllersDir = "./controllers"$OutputFile = "provider/controller_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/controllers"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass ControllerInfo {[string]$ConstructorName # NewAccountController[string]$Domain # AccountController[string]$VarName # accountController[System.Collections.Generic.List[Parameter]]$ParametersControllerInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for controller constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$controllers = [System.Collections.Generic.List[ControllerInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxController(...) XxxController$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Controller)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Controller)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxController)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$controller = [ControllerInfo]::new()$controller.ConstructorName = $constructorName$controller.Domain = $domain$controller.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($controller.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$controller.Parameters.Add($p)}}$controllers.Add($controller)Write-ColorOutput " Found: $constructorName" "Green"}}if ($controllers.Count -eq 0) {Write-ColorOutput "No controller constructors found matching pattern 'NewXxxController'!" "Red"exit 1}Write-ColorOutput "`nTotal controllers discovered: $($controllers.Count)" "Blue"return $controllers}function Resolve-ControllerArgument {param([Parameter]$Param)$type = $Param.NormalizedType# DEPENDENCY RESOLUTION RULES# ============================================# 1. Service pattern: XxxxService -> servicesProvider.ProvideXxxxService()if ($type -match '^(.+)Service$') {$serviceName = $typereturn "servicesProvider.Provide${serviceName}()"}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Config dependency# if ($type -eq "Config") {# return "configProvider.ProvideConfig()"# }## Example: Logger# if ($type -eq "Logger") {# return "loggerProvider.ProvideLogger()"# }## Example: Validator# if ($type -eq "Validator") {# return "validatorProvider.ProvideValidator()"# }# --------------------------------------------# 2. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[ControllerInfo]]$Controllers)Write-ColorOutput "`nGenerating controller provider code..." "Cyan"# Sort controllers alphabetically for consistent output$sortedControllers = $Controllers | Sort-Object -Property Domain$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type ControllerProvider interface {")foreach ($ctrl in $sortedControllers) {$line = "`tProvide$($ctrl.Domain)() controllers.$($ctrl.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type controllerProvider struct {")foreach ($ctrl in $sortedControllers) {$line = "`t$($ctrl.VarName) controllers.$($ctrl.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewControllerProvider(servicesProvider ServicesProvider) ControllerProvider {")[void]$sb.AppendLine()# Initialize controllersforeach ($ctrl in $sortedControllers) {$args = @()foreach ($param in $ctrl.Parameters) {$args += Resolve-ControllerArgument $param}$argsStr = $args -join ", "$line = "`t$($ctrl.VarName) := controllers.$($ctrl.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`treturn &controllerProvider{")foreach ($ctrl in $sortedControllers) {$line = "`t`t$($ctrl.VarName): $($ctrl.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methods[void]$sb.AppendLine("// --- Getter Methods ---")[void]$sb.AppendLine()foreach ($ctrl in $sortedControllers) {[void]$sb.AppendLine("func (c *controllerProvider) Provide$($ctrl.Domain)() controllers.$($ctrl.Domain) {")[void]$sb.AppendLine("`treturn c.$($ctrl.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Controller Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all controller constructors$controllers = Parse-GoFiles -Directory $ControllersDir# Step 2: Generate provider code$code = Generate-ProviderCode -Controllers $controllers# Step 3: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Controller provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Controllers.DESCRIPTIONScans ./controllers/ directory, discovers all controller constructors, infers their dependencies,and generates provider/controller_provider.go with full DI wiring..EXAMPLE.\controller_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Controllers depend on services from ServicesProvider#>[CmdletBinding()]param()# Configuration$ControllersDir = "./controllers"$OutputFile = "provider/controller_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/controllers"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass ControllerInfo {[string]$ConstructorName # NewAccountController[string]$Domain # AccountController[string]$VarName # accountController[System.Collections.Generic.List[Parameter]]$ParametersControllerInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for controller constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$controllers = [System.Collections.Generic.List[ControllerInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxController(...) XxxController$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Controller)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Controller)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxController)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$controller = [ControllerInfo]::new()$controller.ConstructorName = $constructorName$controller.Domain = $domain$controller.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($controller.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$controller.Parameters.Add($p)}}$controllers.Add($controller)Write-ColorOutput " Found: $constructorName" "Green"}}if ($controllers.Count -eq 0) {Write-ColorOutput "No controller constructors found matching pattern 'NewXxxController'!" "Red"exit 1}Write-ColorOutput "`nTotal controllers discovered: $($controllers.Count)" "Blue"return $controllers}function Resolve-ControllerArgument {param([Parameter]$Param)$type = $Param.NormalizedType# DEPENDENCY RESOLUTION RULES# ============================================# 1. Service pattern: XxxxService -> servicesProvider.ProvideXxxxService()if ($type -match '^(.+)Service$') {$serviceName = $typereturn "servicesProvider.Provide${serviceName}()"}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Config dependency# if ($type -eq "Config") {# return "configProvider.ProvideConfig()"# }## Example: Logger# if ($type -eq "Logger") {# return "loggerProvider.ProvideLogger()"# }## Example: Validator# if ($type -eq "Validator") {# return "validatorProvider.ProvideValidator()"# }# --------------------------------------------# 2. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[ControllerInfo]]$Controllers)Write-ColorOutput "`nGenerating controller provider code..." "Cyan"# Sort controllers alphabetically for consistent output$sortedControllers = $Controllers | Sort-Object -Property Domain$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type ControllerProvider interface {")foreach ($ctrl in $sortedControllers) {$line = "`tProvide$($ctrl.Domain)() controllers.$($ctrl.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type controllerProvider struct {")foreach ($ctrl in $sortedControllers) {$line = "`t$($ctrl.VarName) controllers.$($ctrl.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewControllerProvider(servicesProvider ServicesProvider) ControllerProvider {")[void]$sb.AppendLine()# Initialize controllersforeach ($ctrl in $sortedControllers) {$args = @()foreach ($param in $ctrl.Parameters) {$args += Resolve-ControllerArgument $param}$argsStr = $args -join ", "$line = "`t$($ctrl.VarName) := controllers.$($ctrl.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`treturn &controllerProvider{")foreach ($ctrl in $sortedControllers) {$line = "`t`t$($ctrl.VarName): $($ctrl.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methods[void]$sb.AppendLine("// --- Getter Methods ---")[void]$sb.AppendLine()foreach ($ctrl in $sortedControllers) {[void]$sb.AppendLine("func (c *controllerProvider) Provide$($ctrl.Domain)() controllers.$($ctrl.Domain) {")[void]$sb.AppendLine("`treturn c.$($ctrl.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Controller Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all controller constructors$controllers = Parse-GoFiles -Directory $ControllersDir# Step 2: Generate provider code$code = Generate-ProviderCode -Controllers $controllers# Step 3: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Controller provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Middleware.DESCRIPTIONScans ./middleware/ directory, discovers all middleware constructors, infers their dependencies,and generates provider/middleware_provider.go with full DI wiring..EXAMPLE.\middleware_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Middleware depend on services from ServicesProvider#>[CmdletBinding()]param()# Configuration$MiddlewareDir = "./middleware"$OutputFile = "provider/middleware_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/middleware"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass MiddlewareInfo {[string]$ConstructorName # NewAuthenticationMiddleware[string]$Domain # AuthenticationMiddleware[string]$VarName # authenticationMiddleware[System.Collections.Generic.List[Parameter]]$ParametersMiddlewareInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for middleware constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$middlewares = [System.Collections.Generic.List[MiddlewareInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxMiddleware(...) XxxMiddleware$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Middleware)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Middleware)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxMiddleware)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$middleware = [MiddlewareInfo]::new()$middleware.ConstructorName = $constructorName$middleware.Domain = $domain$middleware.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($middleware.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$middleware.Parameters.Add($p)}}$middlewares.Add($middleware)Write-ColorOutput " Found: $constructorName" "Green"}}if ($middlewares.Count -eq 0) {Write-ColorOutput "No middleware constructors found matching pattern 'NewXxxMiddleware'!" "Red"exit 1}Write-ColorOutput "`nTotal middleware discovered: $($middlewares.Count)" "Blue"return $middlewares}function Resolve-MiddlewareArgument {param([Parameter]$Param)$type = $Param.NormalizedType# DEPENDENCY RESOLUTION RULES# ============================================# 1. Service pattern: XxxxService -> servicesProvider.ProvideXxxxService()if ($type -match '^(.+)Service$') {$serviceName = $typereturn "servicesProvider.Provide${serviceName}()"}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Config dependency# if ($type -eq "Config") {# return "configProvider.ProvideConfig()"# }## Example: Logger# if ($type -eq "Logger") {# return "loggerProvider.ProvideLogger()"# }## Example: JWT Config# if ($type -eq "JWTConfig") {# return "configProvider.ProvideJWTConfig()"# }## Example: Database# if ($type -eq "DB" -or $type -eq "Database") {# return "dbProvider.ProvideDatabase()"# }# --------------------------------------------# 2. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[MiddlewareInfo]]$Middlewares)Write-ColorOutput "`nGenerating middleware provider code..." "Cyan"# Sort middleware alphabetically for consistent output$sortedMiddlewares = $Middlewares | Sort-Object -Property Domain$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type MiddlewareProvider interface {")foreach ($mw in $sortedMiddlewares) {$line = "`tProvide$($mw.Domain)() middleware.$($mw.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type middlewareProvider struct {")foreach ($mw in $sortedMiddlewares) {$line = "`t$($mw.VarName) middleware.$($mw.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewMiddlewareProvider(servicesProvider ServicesProvider) MiddlewareProvider {")# Initialize middlewareforeach ($mw in $sortedMiddlewares) {$args = @()foreach ($param in $mw.Parameters) {$args += Resolve-MiddlewareArgument $param}$argsStr = $args -join ", "$line = "`t$($mw.VarName) := middleware.$($mw.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`treturn &middlewareProvider{")foreach ($mw in $sortedMiddlewares) {$line = "`t`t$($mw.VarName): $($mw.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($mw in $sortedMiddlewares) {[void]$sb.AppendLine("func (p *middlewareProvider) Provide$($mw.Domain)() middleware.$($mw.Domain) {")[void]$sb.AppendLine("`treturn p.$($mw.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Middleware Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all middleware constructors$middlewares = Parse-GoFiles -Directory $MiddlewareDir# Step 2: Generate provider code$code = Generate-ProviderCode -Middlewares $middlewares# Step 3: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Middleware provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Middleware.DESCRIPTIONScans ./middleware/ directory, discovers all middleware constructors, infers their dependencies,and generates provider/middleware_provider.go with full DI wiring..EXAMPLE.\middleware_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Middleware depend on services from ServicesProvider#>[CmdletBinding()]param()# Configuration$MiddlewareDir = "./middleware"$OutputFile = "provider/middleware_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/middleware"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass MiddlewareInfo {[string]$ConstructorName # NewAuthenticationMiddleware[string]$Domain # AuthenticationMiddleware[string]$VarName # authenticationMiddleware[System.Collections.Generic.List[Parameter]]$ParametersMiddlewareInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for middleware constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$middlewares = [System.Collections.Generic.List[MiddlewareInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxMiddleware(...) XxxMiddleware$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Middleware)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Middleware)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxMiddleware)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$middleware = [MiddlewareInfo]::new()$middleware.ConstructorName = $constructorName$middleware.Domain = $domain$middleware.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($middleware.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$middleware.Parameters.Add($p)}}$middlewares.Add($middleware)Write-ColorOutput " Found: $constructorName" "Green"}}if ($middlewares.Count -eq 0) {Write-ColorOutput "No middleware constructors found matching pattern 'NewXxxMiddleware'!" "Red"exit 1}Write-ColorOutput "`nTotal middleware discovered: $($middlewares.Count)" "Blue"return $middlewares}function Resolve-MiddlewareArgument {param([Parameter]$Param)$type = $Param.NormalizedType# DEPENDENCY RESOLUTION RULES# ============================================# 1. Service pattern: XxxxService -> servicesProvider.ProvideXxxxService()if ($type -match '^(.+)Service$') {$serviceName = $typereturn "servicesProvider.Provide${serviceName}()"}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Config dependency# if ($type -eq "Config") {# return "configProvider.ProvideConfig()"# }## Example: Logger# if ($type -eq "Logger") {# return "loggerProvider.ProvideLogger()"# }## Example: JWT Config# if ($type -eq "JWTConfig") {# return "configProvider.ProvideJWTConfig()"# }## Example: Database# if ($type -eq "DB" -or $type -eq "Database") {# return "dbProvider.ProvideDatabase()"# }# --------------------------------------------# 2. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[MiddlewareInfo]]$Middlewares)Write-ColorOutput "`nGenerating middleware provider code..." "Cyan"# Sort middleware alphabetically for consistent output$sortedMiddlewares = $Middlewares | Sort-Object -Property Domain$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type MiddlewareProvider interface {")foreach ($mw in $sortedMiddlewares) {$line = "`tProvide$($mw.Domain)() middleware.$($mw.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type middlewareProvider struct {")foreach ($mw in $sortedMiddlewares) {$line = "`t$($mw.VarName) middleware.$($mw.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewMiddlewareProvider(servicesProvider ServicesProvider) MiddlewareProvider {")# Initialize middlewareforeach ($mw in $sortedMiddlewares) {$args = @()foreach ($param in $mw.Parameters) {$args += Resolve-MiddlewareArgument $param}$argsStr = $args -join ", "$line = "`t$($mw.VarName) := middleware.$($mw.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`treturn &middlewareProvider{")foreach ($mw in $sortedMiddlewares) {$line = "`t`t$($mw.VarName): $($mw.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($mw in $sortedMiddlewares) {[void]$sb.AppendLine("func (p *middlewareProvider) Provide$($mw.Domain)() middleware.$($mw.Domain) {")[void]$sb.AppendLine("`treturn p.$($mw.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Middleware Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all middleware constructors$middlewares = Parse-GoFiles -Directory $MiddlewareDir# Step 2: Generate provider code$code = Generate-ProviderCode -Middlewares $middlewares# Step 3: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Middleware provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Repositories.DESCRIPTIONScans ./repositories/ directory, discovers all repository constructors,and generates provider/repositories_provider.go with full DI wiring.Repositories typically depend on database connection from ConfigProvider..EXAMPLE.\repository_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Repositories depend on database instance from ConfigProvider#>[CmdletBinding()]param()# Configuration$RepositoriesDir = "./repositories"$OutputFile = "provider/repositories_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/repositories"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass RepositoryInfo {[string]$ConstructorName # NewAccountRepository[string]$Domain # AccountRepository[string]$VarName # accountRepository[System.Collections.Generic.List[Parameter]]$ParametersRepositoryInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for repository constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$repositories = [System.Collections.Generic.List[RepositoryInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxRepository(...) XxxRepository$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Repository)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Repository)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxRepository)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$repo = [RepositoryInfo]::new()$repo.ConstructorName = $constructorName$repo.Domain = $domain$repo.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($repo.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$repo.Parameters.Add($p)}}$repositories.Add($repo)Write-ColorOutput " Found: $constructorName" "Green"}}if ($repositories.Count -eq 0) {Write-ColorOutput "No repository constructors found matching pattern 'NewXxxRepository'!" "Red"exit 1}Write-ColorOutput "`nTotal repositories discovered: $($repositories.Count)" "Blue"return $repositories}function Resolve-RepositoryArgument {param([Parameter]$Param)$type = $Param.NormalizedType$paramName = $Param.Name# DEPENDENCY RESOLUTION RULES FOR REPOSITORIES# ============================================# 1. Database connection patternsif ($type -match '^(DB|Database|Gorm|SqlDB|Connection)$' -or $paramName -match '^(db|database|conn|connection)$') {return "db"}# 2. *gorm.DB (most common in Go GORM projects)if ($Param.RawType -match 'gorm\.DB' -or $type -eq "DB") {return "db"}# 3. *sql.DB (standard library)if ($Param.RawType -match 'sql\.DB') {return "db"}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Redis connection# if ($type -eq "RedisClient" -or $paramName -match "redis") {# return "redisClient"# }## Example: MongoDB connection# if ($type -eq "MongoClient" -or $paramName -match "mongo") {# return "mongoClient"# }## Example: Cache# if ($type -eq "Cache" -or $paramName -match "cache") {# return "cache"# }## Example: Logger# if ($type -eq "Logger" -or $paramName -match "logger") {# return "logger"# }# --------------------------------------------# 4. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[RepositoryInfo]]$Repositories)Write-ColorOutput "`nGenerating repositories provider code..." "Cyan"# Sort repositories alphabetically for consistent output$sortedRepos = $Repositories | Sort-Object -Property Domain$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type RepositoriesProvider interface {")foreach ($repo in $sortedRepos) {$line = "`tProvide$($repo.Domain)() repositories.$($repo.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type repositoriesProvider struct {")foreach ($repo in $sortedRepos) {$line = "`t$($repo.VarName) repositories.$($repo.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewRepositoriesProvider(cfg ConfigProvider) RepositoriesProvider {")[void]$sb.AppendLine("`tdbConfig := cfg.ProvideDatabaseConfig()")[void]$sb.AppendLine("`tdb := dbConfig.GetInstance()")[void]$sb.AppendLine()# Initialize repositoriesforeach ($repo in $sortedRepos) {$args = @()foreach ($param in $repo.Parameters) {$args += Resolve-RepositoryArgument $param}$argsStr = $args -join ", "$line = "`t$($repo.VarName) := repositories.$($repo.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine()[void]$sb.AppendLine("`treturn &repositoriesProvider{")foreach ($repo in $sortedRepos) {$line = "`t`t$($repo.VarName): $($repo.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($repo in $sortedRepos) {[void]$sb.AppendLine("func (r *repositoriesProvider) Provide$($repo.Domain)() repositories.$($repo.Domain) {")[void]$sb.AppendLine("`treturn r.$($repo.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Repository Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all repository constructors$repositories = Parse-GoFiles -Directory $RepositoriesDir# Step 2: Generate provider code$code = Generate-ProviderCode -Repositories $repositories# Step 3: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Repositories provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Repositories.DESCRIPTIONScans ./repositories/ directory, discovers all repository constructors,and generates provider/repositories_provider.go with full DI wiring.Repositories typically depend on database connection from ConfigProvider..EXAMPLE.\repository_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Repositories depend on database instance from ConfigProvider#>[CmdletBinding()]param()# Configuration$RepositoriesDir = "./repositories"$OutputFile = "provider/repositories_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/repositories"# ANSI colors for better output$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass RepositoryInfo {[string]$ConstructorName # NewAccountRepository[string]$Domain # AccountRepository[string]$VarName # accountRepository[System.Collections.Generic.List[Parameter]]$ParametersRepositoryInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for repository constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$repositories = [System.Collections.Generic.List[RepositoryInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxRepository(...) XxxRepository$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Repository)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Repository)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxRepository)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$repo = [RepositoryInfo]::new()$repo.ConstructorName = $constructorName$repo.Domain = $domain$repo.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($repo.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$repo.Parameters.Add($p)}}$repositories.Add($repo)Write-ColorOutput " Found: $constructorName" "Green"}}if ($repositories.Count -eq 0) {Write-ColorOutput "No repository constructors found matching pattern 'NewXxxRepository'!" "Red"exit 1}Write-ColorOutput "`nTotal repositories discovered: $($repositories.Count)" "Blue"return $repositories}function Resolve-RepositoryArgument {param([Parameter]$Param)$type = $Param.NormalizedType$paramName = $Param.Name# DEPENDENCY RESOLUTION RULES FOR REPOSITORIES# ============================================# 1. Database connection patternsif ($type -match '^(DB|Database|Gorm|SqlDB|Connection)$' -or $paramName -match '^(db|database|conn|connection)$') {return "db"}# 2. *gorm.DB (most common in Go GORM projects)if ($Param.RawType -match 'gorm\.DB' -or $type -eq "DB") {return "db"}# 3. *sql.DB (standard library)if ($Param.RawType -match 'sql\.DB') {return "db"}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Redis connection# if ($type -eq "RedisClient" -or $paramName -match "redis") {# return "redisClient"# }## Example: MongoDB connection# if ($type -eq "MongoClient" -or $paramName -match "mongo") {# return "mongoClient"# }## Example: Cache# if ($type -eq "Cache" -or $paramName -match "cache") {# return "cache"# }## Example: Logger# if ($type -eq "Logger" -or $paramName -match "logger") {# return "logger"# }# --------------------------------------------# 4. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[RepositoryInfo]]$Repositories)Write-ColorOutput "`nGenerating repositories provider code..." "Cyan"# Sort repositories alphabetically for consistent output$sortedRepos = $Repositories | Sort-Object -Property Domain$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type RepositoriesProvider interface {")foreach ($repo in $sortedRepos) {$line = "`tProvide$($repo.Domain)() repositories.$($repo.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type repositoriesProvider struct {")foreach ($repo in $sortedRepos) {$line = "`t$($repo.VarName) repositories.$($repo.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewRepositoriesProvider(cfg ConfigProvider) RepositoriesProvider {")[void]$sb.AppendLine("`tdbConfig := cfg.ProvideDatabaseConfig()")[void]$sb.AppendLine("`tdb := dbConfig.GetInstance()")[void]$sb.AppendLine()# Initialize repositoriesforeach ($repo in $sortedRepos) {$args = @()foreach ($param in $repo.Parameters) {$args += Resolve-RepositoryArgument $param}$argsStr = $args -join ", "$line = "`t$($repo.VarName) := repositories.$($repo.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine()[void]$sb.AppendLine("`treturn &repositoriesProvider{")foreach ($repo in $sortedRepos) {$line = "`t`t$($repo.VarName): $($repo.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($repo in $sortedRepos) {[void]$sb.AppendLine("func (r *repositoriesProvider) Provide$($repo.Domain)() repositories.$($repo.Domain) {")[void]$sb.AppendLine("`treturn r.$($repo.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Repository Provider Generator v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all repository constructors$repositories = Parse-GoFiles -Directory $RepositoriesDir# Step 2: Generate provider code$code = Generate-ProviderCode -Repositories $repositories# Step 3: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Repositories provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Services.DESCRIPTIONScans ./services/ directory, discovers service constructors, resolves dependencies,performs topological sorting, and generates provider/services_provider.go with full DI wiring..EXAMPLE.\service_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Handles dependency cycles with clear error messages#>[CmdletBinding()]param()# Configuration$ServicesDir = "./services"$OutputFile = "provider/services_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/services"# ANSI colors for better output (fallback to plain text if not supported)$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass ServiceInfo {[string]$ConstructorName # NewAccountService[string]$Domain # AccountService[string]$VarName # accountService[System.Collections.Generic.List[Parameter]]$Parameters[System.Collections.Generic.List[string]]$ServiceDependenciesServiceInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()$this.ServiceDependencies = [System.Collections.Generic.List[string]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for service constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$services = [System.Collections.Generic.List[ServiceInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxService(...) XxxService$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Service)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Service)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxService)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$service = [ServiceInfo]::new()$service.ConstructorName = $constructorName$service.Domain = $domain$service.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($service.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$service.Parameters.Add($p)# Track service dependenciesif ($p.NormalizedType -match 'Service$') {$service.ServiceDependencies.Add($p.NormalizedType)}}}$services.Add($service)Write-ColorOutput " Found: $constructorName" "Green"}}if ($services.Count -eq 0) {Write-ColorOutput "No service constructors found matching pattern 'NewXxxService'!" "Red"exit 1}Write-ColorOutput "`nTotal services discovered: $($services.Count)" "Blue"return $services}function Get-TopologicalOrder {param([System.Collections.Generic.List[ServiceInfo]]$Services)Write-ColorOutput "`nBuilding dependency graph..." "Cyan"# Build adjacency list$graph = @{}$inDegree = @{}$domainToService = @{}foreach ($svc in $Services) {$graph[$svc.Domain] = [System.Collections.Generic.List[string]]::new()$inDegree[$svc.Domain] = 0$domainToService[$svc.Domain] = $svc}# Build edgesforeach ($svc in $Services) {foreach ($dep in $svc.ServiceDependencies) {if ($graph.ContainsKey($dep)) {$graph[$dep].Add($svc.Domain)$inDegree[$svc.Domain]++}}}# Kahn's algorithm for topological sort$queue = [System.Collections.Generic.Queue[string]]::new()foreach ($domain in $inDegree.Keys) {if ($inDegree[$domain] -eq 0) {$queue.Enqueue($domain)}}$sorted = [System.Collections.Generic.List[string]]::new()while ($queue.Count -gt 0) {$current = $queue.Dequeue()$sorted.Add($current)foreach ($neighbor in $graph[$current]) {$inDegree[$neighbor]--if ($inDegree[$neighbor] -eq 0) {$queue.Enqueue($neighbor)}}}# Check for cyclesif ($sorted.Count -ne $Services.Count) {$remaining = $inDegree.Keys | Where-Object { $inDegree[$_] -gt 0 }Write-ColorOutput "`nERROR: Circular dependency detected!" "Red"Write-ColorOutput "Services involved in cycle: $($remaining -join ', ')" "Yellow"exit 1}Write-ColorOutput " Dependency graph validated (no cycles)" "Green"Write-ColorOutput " Topological order: $($sorted -join ' -> ')" "Blue"# Return services in topological orderreturn $sorted | ForEach-Object { $domainToService[$_] }}function Resolve-ConstructorArgument {param([Parameter]$Param)$type = $Param.NormalizedType# SPECIAL CASE MAPPINGS - Add more here as needed# ============================================# 1. JWT secret stringif ($Param.RawType -eq "string" -and $Param.Name -match "secret|key") {return "configProvider.ProvideJWTConfig().GetSecretKey()"}# 2. Repository pattern: XxxxRepository -> repoProvider.ProvideXxxxRepository()if ($type -match '^(.+)Repository$') {$repoName = $matches[1]return "repoProvider.Provide${repoName}Repository()"}# 3. Service pattern: XxxxService -> use variable (will be constructed before this)if ($type -match 'Service$') {return (Get-LowerCamelCase $type)}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Mail config# if ($type -eq "MailConfig") {# return "configProvider.ProvideMailConfig()"# }## Example: Redis client# if ($type -eq "RedisClient") {# return "configProvider.ProvideRedisClient()"# }# --------------------------------------------# 4. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[ServiceInfo]]$ServicesInOrder)Write-ColorOutput "`nGenerating provider code..." "Cyan"$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type ServicesProvider interface {")foreach ($svc in $ServicesInOrder) {$line = "`tProvide$($svc.Domain)() services.$($svc.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type servicesProvider struct {")foreach ($svc in $ServicesInOrder) {$line = "`t$($svc.VarName) services.$($svc.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewServicesProvider(repoProvider RepositoriesProvider, configProvider ConfigProvider) ServicesProvider {")# Initialize services in topological orderforeach ($svc in $ServicesInOrder) {$args = @()foreach ($param in $svc.Parameters) {$args += Resolve-ConstructorArgument $param}$argsStr = $args -join ", "$line = "`t$($svc.VarName) := services.$($svc.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine()[void]$sb.AppendLine("`treturn &servicesProvider{")foreach ($svc in $ServicesInOrder) {$line = "`t`t$($svc.VarName): $($svc.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($svc in $ServicesInOrder) {[void]$sb.AppendLine("func (s *servicesProvider) Provide$($svc.Domain)() services.$($svc.Domain) {")[void]$sb.AppendLine("`treturn s.$($svc.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Service Dependency Injector v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all service constructors$services = Parse-GoFiles -Directory $ServicesDir# Step 2: Perform topological sort$sortedServices = Get-TopologicalOrder -Services $services# Step 3: Generate provider code$code = Generate-ProviderCode -ServicesInOrder $sortedServices# Step 4: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383#Requires -Version 5.1<#.SYNOPSISAutomatic Dependency Injection Generator for Go Services.DESCRIPTIONScans ./services/ directory, discovers service constructors, resolves dependencies,performs topological sorting, and generates provider/services_provider.go with full DI wiring..EXAMPLE.\service_injector.ps1.NOTES- Works with PowerShell 5.1+ and PowerShell 7+- No external dependencies required- Supports multi-line constructor signatures- Handles dependency cycles with clear error messages#>[CmdletBinding()]param()# Configuration$ServicesDir = "./services"$OutputFile = "provider/services_provider.go"$ModulePath = "abdanhafidz.com/go-boilerplate/services"# ANSI colors for better output (fallback to plain text if not supported)$script:UseColors = $Host.UI.SupportsVirtualTerminalfunction Write-ColorOutput {param([string]$Message, [string]$Color = "White")if ($script:UseColors) {$colors = @{"Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m""Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"}Write-Host "$($colors[$Color])$Message$($colors['Reset'])"} else {Write-Host $Message}}# Data structuresclass ServiceInfo {[string]$ConstructorName # NewAccountService[string]$Domain # AccountService[string]$VarName # accountService[System.Collections.Generic.List[Parameter]]$Parameters[System.Collections.Generic.List[string]]$ServiceDependenciesServiceInfo() {$this.Parameters = [System.Collections.Generic.List[Parameter]]::new()$this.ServiceDependencies = [System.Collections.Generic.List[string]]::new()}}class Parameter {[string]$Name[string]$RawType[string]$NormalizedType}function Get-LowerCamelCase {param([string]$Text)if ($Text.Length -eq 0) { return $Text }return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)}function Normalize-TypeName {param([string]$TypeStr)# Remove leading pointer$cleaned = $TypeStr -replace '^\*+', ''# Remove package prefix (everything before last dot)if ($cleaned -match '\.([^.]+)$') {$cleaned = $matches[1]}return $cleaned.Trim()}function Parse-GoFiles {param([string]$Directory)Write-ColorOutput "Scanning for service constructors in $Directory..." "Cyan"if (-not (Test-Path $Directory)) {Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"exit 1}$goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File$services = [System.Collections.Generic.List[ServiceInfo]]::new()foreach ($file in $goFiles) {$content = Get-Content $file.FullName -Raw# Match function signatures (support multi-line)# Pattern: func NewXxxService(...) XxxService$pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Service)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Service)'$matches = [regex]::Matches($content, $pattern)foreach ($match in $matches) {$constructorName = $match.Groups[1].Value$paramsStr = $match.Groups[2].Value$returnType = $match.Groups[3].Value# Extract domain name (XxxService)$domain = Normalize-TypeName $returnType$varName = Get-LowerCamelCase $domain$service = [ServiceInfo]::new()$service.ConstructorName = $constructorName$service.Domain = $domain$service.VarName = $varName# Parse parametersif ($paramsStr.Trim() -ne "") {# Split by comma, but be careful with nested types$paramList = $paramsStr -split ',\s*(?![^<>]*>)'foreach ($param in $paramList) {$param = $param.Trim()if ($param -eq "") { continue }# Split into name and type$parts = $param -split '\s+', 2$p = [Parameter]::new()if ($parts.Count -eq 2) {$p.Name = $parts[0]$p.RawType = $parts[1]} elseif ($parts.Count -eq 1) {# Anonymous parameter - synthesize name$p.Name = "param$($service.Parameters.Count)"$p.RawType = $parts[0]} else {continue}$p.NormalizedType = Normalize-TypeName $p.RawType$service.Parameters.Add($p)# Track service dependenciesif ($p.NormalizedType -match 'Service$') {$service.ServiceDependencies.Add($p.NormalizedType)}}}$services.Add($service)Write-ColorOutput " Found: $constructorName" "Green"}}if ($services.Count -eq 0) {Write-ColorOutput "No service constructors found matching pattern 'NewXxxService'!" "Red"exit 1}Write-ColorOutput "`nTotal services discovered: $($services.Count)" "Blue"return $services}function Get-TopologicalOrder {param([System.Collections.Generic.List[ServiceInfo]]$Services)Write-ColorOutput "`nBuilding dependency graph..." "Cyan"# Build adjacency list$graph = @{}$inDegree = @{}$domainToService = @{}foreach ($svc in $Services) {$graph[$svc.Domain] = [System.Collections.Generic.List[string]]::new()$inDegree[$svc.Domain] = 0$domainToService[$svc.Domain] = $svc}# Build edgesforeach ($svc in $Services) {foreach ($dep in $svc.ServiceDependencies) {if ($graph.ContainsKey($dep)) {$graph[$dep].Add($svc.Domain)$inDegree[$svc.Domain]++}}}# Kahn's algorithm for topological sort$queue = [System.Collections.Generic.Queue[string]]::new()foreach ($domain in $inDegree.Keys) {if ($inDegree[$domain] -eq 0) {$queue.Enqueue($domain)}}$sorted = [System.Collections.Generic.List[string]]::new()while ($queue.Count -gt 0) {$current = $queue.Dequeue()$sorted.Add($current)foreach ($neighbor in $graph[$current]) {$inDegree[$neighbor]--if ($inDegree[$neighbor] -eq 0) {$queue.Enqueue($neighbor)}}}# Check for cyclesif ($sorted.Count -ne $Services.Count) {$remaining = $inDegree.Keys | Where-Object { $inDegree[$_] -gt 0 }Write-ColorOutput "`nERROR: Circular dependency detected!" "Red"Write-ColorOutput "Services involved in cycle: $($remaining -join ', ')" "Yellow"exit 1}Write-ColorOutput " Dependency graph validated (no cycles)" "Green"Write-ColorOutput " Topological order: $($sorted -join ' -> ')" "Blue"# Return services in topological orderreturn $sorted | ForEach-Object { $domainToService[$_] }}function Resolve-ConstructorArgument {param([Parameter]$Param)$type = $Param.NormalizedType# SPECIAL CASE MAPPINGS - Add more here as needed# ============================================# 1. JWT secret stringif ($Param.RawType -eq "string" -and $Param.Name -match "secret|key") {return "configProvider.ProvideJWTConfig().GetSecretKey()"}# 2. Repository pattern: XxxxRepository -> repoProvider.ProvideXxxxRepository()if ($type -match '^(.+)Repository$') {$repoName = $matches[1]return "repoProvider.Provide${repoName}Repository()"}# 3. Service pattern: XxxxService -> use variable (will be constructed before this)if ($type -match 'Service$') {return (Get-LowerCamelCase $type)}# ADD MORE SPECIAL CASES HERE:# --------------------------------------------# Example: Mail config# if ($type -eq "MailConfig") {# return "configProvider.ProvideMailConfig()"# }## Example: Redis client# if ($type -eq "RedisClient") {# return "configProvider.ProvideRedisClient()"# }# --------------------------------------------# 4. Fallback: unresolved typereturn "/* TODO: provide $($Param.RawType) */"}function Generate-ProviderCode {param([System.Collections.Generic.List[ServiceInfo]]$ServicesInOrder)Write-ColorOutput "`nGenerating provider code..." "Cyan"$sb = [System.Text.StringBuilder]::new()[void]$sb.AppendLine("package provider")[void]$sb.AppendLine()[void]$sb.AppendLine("import `"$ModulePath`"")[void]$sb.AppendLine()# Interface[void]$sb.AppendLine("type ServicesProvider interface {")foreach ($svc in $ServicesInOrder) {$line = "`tProvide$($svc.Domain)() services.$($svc.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Struct[void]$sb.AppendLine("type servicesProvider struct {")foreach ($svc in $ServicesInOrder) {$line = "`t$($svc.VarName) services.$($svc.Domain)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Constructor[void]$sb.AppendLine("func NewServicesProvider(repoProvider RepositoriesProvider, configProvider ConfigProvider) ServicesProvider {")# Initialize services in topological orderforeach ($svc in $ServicesInOrder) {$args = @()foreach ($param in $svc.Parameters) {$args += Resolve-ConstructorArgument $param}$argsStr = $args -join ", "$line = "`t$($svc.VarName) := services.$($svc.ConstructorName)($argsStr)"[void]$sb.AppendLine($line)}[void]$sb.AppendLine()[void]$sb.AppendLine("`treturn &servicesProvider{")foreach ($svc in $ServicesInOrder) {$line = "`t`t$($svc.VarName): $($svc.VarName),"[void]$sb.AppendLine($line)}[void]$sb.AppendLine("`t}")[void]$sb.AppendLine("}")[void]$sb.AppendLine()# Getter methodsforeach ($svc in $ServicesInOrder) {[void]$sb.AppendLine("func (s *servicesProvider) Provide$($svc.Domain)() services.$($svc.Domain) {")[void]$sb.AppendLine("`treturn s.$($svc.VarName)")[void]$sb.AppendLine("}")[void]$sb.AppendLine()}return $sb.ToString()}function Write-ProviderFile {param([string]$Code, [string]$OutputPath)Write-ColorOutput "Writing to $OutputPath..." "Cyan"# Ensure directory exists$dir = Split-Path $OutputPath -Parentif ($dir -and -not (Test-Path $dir)) {New-Item -ItemType Directory -Path $dir -Force | Out-Null}# Write file as UTF-8 without BOM$utf8NoBom = [System.Text.UTF8Encoding]::new($false)[System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)Write-ColorOutput " Successfully generated $OutputPath" "Green"}# ============================================# MAIN EXECUTION# ============================================try {Write-ColorOutput "`n=========================================" "Blue"Write-ColorOutput " Go Service Dependency Injector v1.0" "Blue"Write-ColorOutput "=========================================`n" "Blue"# Step 1: Parse all service constructors$services = Parse-GoFiles -Directory $ServicesDir# Step 2: Perform topological sort$sortedServices = Get-TopologicalOrder -Services $services# Step 3: Generate provider code$code = Generate-ProviderCode -ServicesInOrder $sortedServices# Step 4: Write to fileWrite-ProviderFile -Code $code -OutputPath $OutputFileWrite-ColorOutput "`nSUCCESS! Provider generated successfully.`n" "Green"Write-ColorOutput "Next steps:" "Cyan"Write-ColorOutput " 1. Review $OutputFile" "White"Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"Write-ColorOutput " 3. Run: go build ./provider" "White"} catch {Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"exit 1}
56 unmodified lines57585960616256 unmodified linesgithub.com/quic-go/qpack v0.5.1 // indirectgithub.com/quic-go/quic-go v0.55.0 // indirectgithub.com/rogpeppe/go-internal v1.14.1 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.3.0 // indirectgo.opentelemetry.io/auto/sdk v1.1.0 // indirect56 unmodified lines5758596061626356 unmodified linesgithub.com/quic-go/qpack v0.5.1 // indirectgithub.com/quic-go/quic-go v0.55.0 // indirectgithub.com/rogpeppe/go-internal v1.14.1 // indirectgithub.com/supabase-community/storage-go v0.8.1 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.3.0 // indirectgo.opentelemetry.io/auto/sdk v1.1.0 // indirect
139 unmodified lines140141142143144145139 unmodified linesgithub.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=139 unmodified lines140141142143144145146147139 unmodified linesgithub.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/supabase-community/storage-go v0.8.1 h1:EwD0vr+ADBIjBWH8G69AxWuvdFhifv64cfE/sjRky6I=github.com/supabase-community/storage-go v0.8.1/go.mod h1:oBKcJf5rcUXy3Uj9eS5wR6mvpwbmvkjOtAA+4tGcdvQ=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748package middlewareimport ("errors""fmt""strings"http_error "abdanhafidz.com/go-boilerplate/models/error""abdanhafidz.com/go-boilerplate/services"utils "abdanhafidz.com/go-boilerplate/utils""github.com/gin-gonic/gin")type AuthenticationMiddleware interface {VerifyAccount(ctx *gin.Context)}type authenticationMiddleware struct {jwtService services.JWTService}func NewAuthenticationMiddleware(jwtService services.JWTService) AuthenticationMiddleware {return &authenticationMiddleware{jwtService: jwtService,}}func (m *authenticationMiddleware) VerifyAccount(c *gin.Context) {authorizationBearer := c.Request.Header["Authorization"]if authorizationBearer != nil {token := strings.Split(authorizationBearer[0], " ")[1]claim, err := m.jwtService.ValidateToken(c.Request.Context(), token)if err != nil && errors.Is(err, http_error.INVALID_TOKEN) {utils.ResponseFAILED(c, claim, http_error.INVALID_TOKEN)c.Abort()return}fmt.Println("Claims:", claim)c.Set("account_id", claim.AccountId)c.Next()} else {utils.ResponseFAILED(c, "Empty Token", http_error.UNAUTHORIZED)return}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748package middlewareimport ("errors""fmt""strings"http_error "abdanhafidz.com/go-boilerplate/models/error""abdanhafidz.com/go-boilerplate/services"utils "abdanhafidz.com/go-boilerplate/utils""github.com/gin-gonic/gin")type AuthenticationMiddleware interface {VerifyAccount(ctx *gin.Context)}type authenticationMiddleware struct {jwtService services.JWTService}func NewAuthenticationMiddleware(jwtService services.JWTService) AuthenticationMiddleware {return &authenticationMiddleware{jwtService: jwtService,}}func (m *authenticationMiddleware) VerifyAccount(c *gin.Context) {authorizationBearer := c.Request.Header["Authorization"]if authorizationBearer != nil {token := strings.Split(authorizationBearer[0], " ")[1]claim, err := m.jwtService.ValidateToken(c.Request.Context(), token)if err != nil && errors.Is(err, http_error.INVALID_TOKEN) {utils.ResponseFAILED(c, claim, http_error.INVALID_TOKEN)c.Abort()return}fmt.Println("Claims:", claim)c.Set("account_id", claim.AccountId)c.Next()} else {utils.ResponseFAILED(c, "Empty Token", http_error.UNAUTHORIZED)return}}
12345678910111213141516171819202122232425262728293031323334353637383940414243package middlewareimport (http_error "abdanhafidz.com/go-boilerplate/models/error""abdanhafidz.com/go-boilerplate/services"utils "abdanhafidz.com/go-boilerplate/utils""github.com/gin-gonic/gin""github.com/google/uuid")type AuthorizationMiddleware interface {AuthorizeUserToEvent(ctx *gin.Context)}type authorizationMiddleware struct {eventService services.EventService}func NewAuthorizationMiddleware(eventService services.EventService) AuthorizationMiddleware {return &authorizationMiddleware{eventService: eventService,}}func (m *authorizationMiddleware) AuthorizeUserToEvent(c *gin.Context) {eventSlug := c.Param("slug")accountId, exists := c.Get("account_id")if !exists {utils.ResponseFAILED(c, eventSlug, http_error.DATA_NOT_FOUND)c.Abort()return}err := m.eventService.AuthorizeUserToEvent(c.Request.Context(), eventSlug, accountId.(uuid.UUID))if err != nil {utils.ResponseFAILED(c, eventSlug, err)c.Abort()return}c.Next()}12345678910111213141516171819202122232425262728293031323334353637383940414243package middlewareimport (http_error "abdanhafidz.com/go-boilerplate/models/error""abdanhafidz.com/go-boilerplate/services"utils "abdanhafidz.com/go-boilerplate/utils""github.com/gin-gonic/gin""github.com/google/uuid")type AuthorizationMiddleware interface {AuthorizeUserToEvent(ctx *gin.Context)}type authorizationMiddleware struct {eventService services.EventService}func NewAuthorizationMiddleware(eventService services.EventService) AuthorizationMiddleware {return &authorizationMiddleware{eventService: eventService,}}func (m *authorizationMiddleware) AuthorizeUserToEvent(c *gin.Context) {eventSlug := c.Param("slug")accountId, exists := c.Get("account_id")if !exists {utils.ResponseFAILED(c, eventSlug, http_error.NOT_FOUND_ERROR)c.Abort()return}err := m.eventService.AuthorizeUserToEvent(c.Request.Context(), eventSlug, accountId.(uuid.UUID))if err != nil {utils.ResponseFAILED(c, eventSlug, err)c.Abort()return}c.Next()}
1package middleware1package middleware
123456789101112131415161718192021222324252627282930package dtoimport "github.com/google/uuid"type CreateAcademyRequest struct {Title string `json:"title" binding:"required"`Slug string `json:"slug"`Description string `json:"description"`ImageUrl string `json:"image_url"`}type UpdateAcademyRequest struct {Title string `json:"title"`Slug string `json:"slug"`Description string `json:"description"`ImageUrl string `json:"image_url"`}type CreateMaterialRequest struct {AcademyId uuid.UUID `json:"academy_id" binding:"required"`Title string `json:"title" binding:"required"`Slug string `json:"slug"`Description string `json:"description"`}type CreateContentRequest struct {MaterialId uuid.UUID `json:"material_id" binding:"required"`Title string `json:"title" binding:"required"`Contents string `json:"contents"`}123456789101112131415161718192021222324252627282930package dtoimport "github.com/google/uuid"type CreateAcademyRequest struct {Title string `json:"title" binding:"required"`Slug string `json:"slug"`Description string `json:"description"`ImageUrl string `json:"image_url"`}type UpdateAcademyRequest struct {Title string `json:"title"`Slug string `json:"slug"`Description string `json:"description"`ImageUrl string `json:"image_url"`}type CreateMaterialRequest struct {AcademyId uuid.UUID `json:"academy_id" binding:"required"`Title string `json:"title" binding:"required"`Slug string `json:"slug"`Description string `json:"description"`}type CreateContentRequest struct {MaterialId uuid.UUID `json:"material_id" binding:"required"`Title string `json:"title" binding:"required"`Contents string `json:"contents"`}
12345678910111213141516171819package dtoimport (entity "abdanhafidz.com/go-boilerplate/models/entity")type AccountDetailResponse struct {Account entity.Account `json:"account"`Details entity.AccountDetail `json:"details"`}type UpdateAccountDetailRequest struct {FullName *string `json:"full_name"`SchoolName *string `json:"school_name"`Province *string `json:"province"`City *string `json:"city"`Avatar *string `json:"avatar"`PhoneNumber *string `json:"phone_number"`}12345678910111213141516171819package dtoimport (entity "abdanhafidz.com/go-boilerplate/models/entity")type AccountDetailResponse struct {Account entity.Account `json:"account"`Details entity.AccountDetail `json:"details"`}type UpdateAccountDetailRequest struct {FullName *string `json:"full_name"`SchoolName *string `json:"school_name"`Province *string `json:"province"`City *string `json:"city"`Avatar *string `json:"avatar"`PhoneNumber *string `json:"phone_number"`}
1234567891011121314151617181920package dtoimport (entity "abdanhafidz.com/go-boilerplate/models/entity")type EventDetailResponse struct {Data *entity.EventsRegisterStatus int `json:"register_status" binding:"required"`}type JoinEventRequest struct {EventCode string `json:"event_code" binding:"required"`}type EventStatus struct {IsHasNotStarted boolIsOnGoing boolIsFinished bool}1234567891011121314151617181920package dtoimport (entity "abdanhafidz.com/go-boilerplate/models/entity")type EventDetailResponse struct {Data *entity.EventsRegisterStatus int `json:"register_status" binding:"required"`}type JoinEventRequest struct {EventCode string `json:"event_code" binding:"required"`}type EventStatus struct {IsHasNotStarted boolIsOnGoing boolIsFinished bool}
1234567891011121314151617181920212223package dtoimport (entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid")type UserExamStatus struct {IsNotAttempt boolIsOnAttempt boolIsSubmitted boolIsTimeOut bool}type AnswerWithQuestion struct {Answer entity.ExamEventAnswer `json:"answer"`Question entity.Questions `json:"question"`}type AnswerExamEventRequest struct {QuestionId uuid.UUID `json:"question_id" binding:"required"`Answer []string `json:"answer"`}1234567891011121314151617181920212223package dtoimport (entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid")type UserExamStatus struct {IsNotAttempt boolIsOnAttempt boolIsSubmitted boolIsTimeOut bool}type AnswerWithQuestion struct {Answer entity.ExamEventAnswer `json:"answer"`Question entity.Questions `json:"question"`}type AnswerExamEventRequest struct {QuestionId uuid.UUID `json:"question_id" binding:"required"`Answer []string `json:"answer"`}
123456789101112package dtoimport entity "abdanhafidz.com/go-boilerplate/models/entity"type OptionsRequest struct {OptionName string `json:"option_name" binding:"required"`OptionValue []string `json:"option_values" binding:"required"`}type OptionsResponse struct {Options []entity.Options `json:"options"`}123456789101112package dtoimport entity "abdanhafidz.com/go-boilerplate/models/entity"type OptionsRequest struct {OptionName string `json:"option_name" binding:"required"`OptionValue []string `json:"option_values" binding:"required"`}type OptionsResponse struct {Options []entity.Options `json:"options"`}
12345678910111213141516171819202122232425262728293031323334353637383940414243package dto
import ( // Gunakan path yang SAMA PERSIS dengan yang ada di OptionsRequest entity "abdanhafidz.com/go-boilerplate/models/entity"
"github.com/google/uuid" "time")
type FileResponse struct { Id uuid.UUID `json:"id"` OriginalName string `json:"original_name"` URL string `json:"url"` MimeType string `json:"mime_type"` Size int64 `json:"size"` CreatedAt time.Time `json:"created_at"`}
type FileUploadResponse struct { Status string `json:"status"` Message string `json:"message"` Data []FileResponse `json:"data"`}
type FileResponseSingle struct { Status string `json:"status"` Message string `json:"message"` Data FileResponse `json:"data"`}
func FormatFileResponse(f *entity.File, baseURL string) FileResponse { fullURL := baseURL + f.Path
return FileResponse{ Id: f.Id, OriginalName: f.OriginalName, URL: fullURL, MimeType: f.MimeType, Size: f.Size, CreatedAt: f.CreatedAt, }}1234567package models
const ( StatusNotStarted = "NOT_STARTED" StatusInProgress = "IN_PROGRESS" StatusCompleted = "COMPLETED")331 unmodified lines332333334331 unmodified lines}func (AcademyContentProgress) TableName() string { return "academy_content_progress" }331 unmodified lines332333334335336337338339340341342343344345346347348349331 unmodified lines}func (AcademyContentProgress) TableName() string { return "academy_content_progress" }type File struct {Id uuid.UUID `gorm:"type:uuid;primary_key;default:uuid_generate_v4()" json:"id"`OriginalName string `json:"original_name,omitempty"`StoredName string `json:"stored_name,omitempty"`MimeType string `json:"mime_type,omitempty"`Size int64 `json:"size,omitempty"`Path string `json:"path,omitempty"`Context string `json:"context,omitempty"`AccountId uuid.UUID `json:"account_id,omitempty"`CreatedAt time.Time `json:"created_at,omitempty"`Account *Account `gorm:"foreignKey:AccountId" json:"account,omitempty"`}func (File) TableName() string { return "files" }
2 unmodified lines34567891011121314151617181920212223242526272 unmodified linesimport "errors"var (BAD_REQUEST_ERROR = errors.New("Invalid Request Format !")INTERNAL_SERVER_ERROR = errors.New("Internal Server Error!")UNAUTHORIZED = errors.New("Unauthorized, you don't have permission to access this service!")DATA_NOT_FOUND = errors.New("There is not data with given credential / given parameter!")TIMEOUT = errors.New("Server took to long respond!")EXISTING_ACCOUNT = errors.New("There is existing account!")INVALID_TOKEN = errors.New("Invalid Authentication Payload!")DUPLICATE_DATA = errors.New("Duplicate data !")ACCOUNT_NOT_FOUND = errors.New("There is no account with given credential!")WRONG_PASSWORD = errors.New("Your password is wrong for given account credential, please recheck!")INVALID_ACCOUNT_DIGITS = errors.New("Your account 3 digits is not found in account number data")EXPIRED_TOKEN = errors.New("Token expired")ALREADY_REGISTERED_TO_EVENT = errors.New("Account already registered to this event")EMAIL_ALREADY_EXISTS = errors.New("Email already registered")NOT_REGISTERED_TO_EVENT = errors.New("Account is not registered to this event")INVALID_OTP = errors.New("Invalid OTP Code")ERR_PROBLEM_SET_NOT_FOUND = errors.New("problem set not found")ERR_QUESTION_NOT_FOUND = errors.New("question not found")EVENT_FINISHED = errors.New("The event has ended, you were disallowed to do the exam!")EVENT_NOT_STARTED = errors.New("Take it easy, event hasn't starting yet! you cannot do the exam!")EXAMS_SUBMITTED = errors.New("You've submitted the exam, you were diasallowed to answer the question!"))2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950512 unmodified linesimport "errors"var (// ================= GENERAL =================BAD_REQUEST_ERROR = errors.New("Invalid Request Format !")INTERNAL_SERVER_ERROR = errors.New("Internal Server Error!")TIMEOUT = errors.New("Server took to long respond!")NOT_FOUND_ERROR = errors.New("Resource not found.")DUPLICATE_DATA = errors.New("Duplicate data !")INVALID_DATA_PAYLOAD = errors.New("Invalid data payload provided.")// ================= AUTH & ACCOUNT =================UNAUTHORIZED = errors.New("Unauthorized, you don't have permission to access this service!")EXISTING_ACCOUNT = errors.New("There is existing account!")INVALID_TOKEN = errors.New("Invalid Authentication Payload!")ACCOUNT_NOT_FOUND = errors.New("There is no account with given credential!")WRONG_PASSWORD = errors.New("Your password is wrong for given account credential, please recheck!")INVALID_ACCOUNT_DIGITS = errors.New("Your account 3 digits is not found in account number data")EXPIRED_TOKEN = errors.New("Token expired")INVALID_OTP = errors.New("Invalid OTP Code")EMAIL_ALREADY_EXISTS = errors.New("Email already registered")// ================= EVENT & EXAM =================ALREADY_REGISTERED_TO_EVENT = errors.New("Account already registered to this event")NOT_REGISTERED_TO_EVENT = errors.New("Account is not registered to this event")ERR_PROBLEM_SET_NOT_FOUND = errors.New("problem set not found")ERR_QUESTION_NOT_FOUND = errors.New("question not found")EVENT_FINISHED = errors.New("The event has ended, you were disallowed to do the exam!")EVENT_NOT_STARTED = errors.New("Take it easy, event hasn't starting yet! you cannot do the exam!")EXAMS_SUBMITTED = errors.New("You've submitted the exam, you were diasallowed to answer the question!")// ================= FILE UPLOAD =================FILE_TOO_LARGE = errors.New("File size exceeds the maximum limit!")INVALID_FILE_TYPE = errors.New("File type is not permitted for the selected context.")UPLOAD_FAILED = errors.New("Failed to upload file to storage provider.")PARTIAL_UPLOAD_FAILURE = errors.New("Some files failed validation or upload.")// ================= ACADEMY =================TITLE_REQUIRED = errors.New("Title cannot be empty!")SLUG_REQUIRED = errors.New("Slug cannot be empty!")ACADEMY_ID_REQUIRED = errors.New("Academy ID is required!")MATERIAL_ID_REQUIRED = errors.New("Material ID is required!")ACADEMY_NOT_FOUND = errors.New("Academy not found!")MATERIAL_NOT_FOUND = errors.New("Material not found!")CONTENT_NOT_FOUND = errors.New("Content not found!")ACADEMY_HAS_MATERIALS = errors.New("Cannot delete academy because it still has materials!")MATERIAL_HAS_CONTENTS = errors.New("Cannot delete material because it still has contents!"))
1234567891011121314151617181920212223242526272829303132333435363738package providerimport "abdanhafidz.com/go-boilerplate/config"type ConfigProvider interface {ProvideJWTConfig() config.JWTConfigProvideEnvConfig() config.EnvConfigProvideDatabaseConfig() config.DatabaseConfig}type configProvider struct {jWTConfig config.JWTConfigenvConfig config.EnvConfigdatabaseConfig config.DatabaseConfig}func NewConfigProvider() ConfigProvider {envConfig := config.NewEnvConfig("Asia/Jakarta")jWTConfig := config.NewJWTConfig(envConfig.GetSalt())databaseConfig := config.NewDatabaseConfig(envConfig.GetDatabaseHost(), envConfig.GetDatabaseUser(), envConfig.GetDatabasePassword(), envConfig.GetDatabaseName(), envConfig.GetDatabasePort())return &configProvider{jWTConfig: jWTConfig,envConfig: envConfig,databaseConfig: databaseConfig,}}func (c *configProvider) ProvideJWTConfig() config.JWTConfig {return c.jWTConfig}func (c *configProvider) ProvideEnvConfig() config.EnvConfig {return c.envConfig}func (c *configProvider) ProvideDatabaseConfig() config.DatabaseConfig {return c.databaseConfig}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859package providerimport "abdanhafidz.com/go-boilerplate/config"type ConfigProvider interface {ProvideJWTConfig() config.JWTConfigProvideEnvConfig() config.EnvConfigProvideDatabaseConfig() config.DatabaseConfigProvideSupabaseConfig() config.SupabaseConfig}type configProvider struct {jWTConfig config.JWTConfigenvConfig config.EnvConfigdatabaseConfig config.DatabaseConfigsupabaseConfig config.SupabaseConfig}func NewConfigProvider() ConfigProvider {envConfig := config.NewEnvConfig("Asia/Jakarta")jWTConfig := config.NewJWTConfig(envConfig.GetSalt())databaseConfig := config.NewDatabaseConfig(envConfig.GetDatabaseHost(),envConfig.GetDatabaseUser(),envConfig.GetDatabasePassword(),envConfig.GetDatabaseName(),envConfig.GetDatabasePort(),)supabaseConfig := config.NewSupabaseConfig(envConfig.GetSupabaseURL(),envConfig.GetSupabaseKey(),envConfig.GetSupabaseBucket(),)return &configProvider{jWTConfig: jWTConfig,envConfig: envConfig,databaseConfig: databaseConfig,supabaseConfig: supabaseConfig,}}func (c *configProvider) ProvideJWTConfig() config.JWTConfig {return c.jWTConfig}func (c *configProvider) ProvideEnvConfig() config.EnvConfig {return c.envConfig}func (c *configProvider) ProvideDatabaseConfig() config.DatabaseConfig {return c.databaseConfig}func (c *configProvider) ProvideSupabaseConfig() config.SupabaseConfig {return c.supabaseConfig}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990package providerimport "abdanhafidz.com/go-boilerplate/controllers"type ControllerProvider interface {ProvideAcademyController() controllers.AcademyControllerProvideAccountDetailController() controllers.AccountDetailControllerProvideAuthenticationController() controllers.AuthenticationControllerProvideEmailVerificationController() controllers.EmailVerificationControllerProvideEventController() controllers.EventControllerProvideExamController() controllers.ExamControllerProvideForgotPasswordController() controllers.ForgotPasswordControllerProvideOptionController() controllers.OptionControllerProvideRegionController() controllers.RegionController}type controllerProvider struct {academyController controllers.AcademyControlleraccountDetailController controllers.AccountDetailControllerauthenticationController controllers.AuthenticationControlleremailVerificationController controllers.EmailVerificationControllereventController controllers.EventControllerexamController controllers.ExamControllerforgotPasswordController controllers.ForgotPasswordControlleroptionController controllers.OptionControllerregionController controllers.RegionController}func NewControllerProvider(servicesProvider ServicesProvider) ControllerProvider {academyController := controllers.NewAcademyController(servicesProvider.ProvideAcademyService())accountDetailController := controllers.NewAccountDetailController(servicesProvider.ProvideAccountService())authenticationController := controllers.NewAuthenticationController(servicesProvider.ProvideAccountService(), servicesProvider.ProvideExternalAuthService())emailVerificationController := controllers.NewEmailVerificationController(servicesProvider.ProvideEmailVerificationService())eventController := controllers.NewEventController(servicesProvider.ProvideEventService())examController := controllers.NewExamController(servicesProvider.ProvideExamService())forgotPasswordController := controllers.NewForgotPasswordController(servicesProvider.ProvideForgotPasswordService())optionController := controllers.NewOptionController(servicesProvider.ProvideOptionService())regionController := controllers.NewRegionController(servicesProvider.ProvideRegionService())return &controllerProvider{academyController: academyController,accountDetailController: accountDetailController,authenticationController: authenticationController,emailVerificationController: emailVerificationController,eventController: eventController,examController: examController,forgotPasswordController: forgotPasswordController,optionController: optionController,regionController: regionController,}}// --- Getter Methods ---func (c *controllerProvider) ProvideAcademyController() controllers.AcademyController {return c.academyController}func (c *controllerProvider) ProvideAccountDetailController() controllers.AccountDetailController {return c.accountDetailController}func (c *controllerProvider) ProvideAuthenticationController() controllers.AuthenticationController {return c.authenticationController}func (c *controllerProvider) ProvideEmailVerificationController() controllers.EmailVerificationController {return c.emailVerificationController}func (c *controllerProvider) ProvideEventController() controllers.EventController {return c.eventController}func (c *controllerProvider) ProvideExamController() controllers.ExamController {return c.examController}func (c *controllerProvider) ProvideForgotPasswordController() controllers.ForgotPasswordController {return c.forgotPasswordController}func (c *controllerProvider) ProvideOptionController() controllers.OptionController {return c.optionController}func (c *controllerProvider) ProvideRegionController() controllers.RegionController {return c.regionController}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106package providerimport "abdanhafidz.com/go-boilerplate/controllers"type ControllerProvider interface {ProvideAcademyController() controllers.AcademyControllerProvideAccountDetailController() controllers.AccountDetailControllerProvideAuthenticationController() controllers.AuthenticationControllerProvideEmailVerificationController() controllers.EmailVerificationControllerProvideEventController() controllers.EventControllerProvideExamController() controllers.ExamControllerProvideForgotPasswordController() controllers.ForgotPasswordControllerProvideOptionController() controllers.OptionControllerProvideRegionController() controllers.RegionController// UPDATE: Menggunakan Pointer (*)ProvideUploadController() *controllers.UploadController}type controllerProvider struct {academyController controllers.AcademyControlleraccountDetailController controllers.AccountDetailControllerauthenticationController controllers.AuthenticationControlleremailVerificationController controllers.EmailVerificationControllereventController controllers.EventControllerexamController controllers.ExamControllerforgotPasswordController controllers.ForgotPasswordControlleroptionController controllers.OptionControllerregionController controllers.RegionController// UPDATE: Menggunakan Pointer (*)uploadController *controllers.UploadController}func NewControllerProvider(servicesProvider ServicesProvider) ControllerProvider {academyController := controllers.NewAcademyController(servicesProvider.ProvideAcademyService())accountDetailController := controllers.NewAccountDetailController(servicesProvider.ProvideAccountService())authenticationController := controllers.NewAuthenticationController(servicesProvider.ProvideAccountService(), servicesProvider.ProvideExternalAuthService())emailVerificationController := controllers.NewEmailVerificationController(servicesProvider.ProvideEmailVerificationService())eventController := controllers.NewEventController(servicesProvider.ProvideEventService())examController := controllers.NewExamController(servicesProvider.ProvideExamService())forgotPasswordController := controllers.NewForgotPasswordController(servicesProvider.ProvideForgotPasswordService())optionController := controllers.NewOptionController(servicesProvider.ProvideOptionService())regionController := controllers.NewRegionController(servicesProvider.ProvideRegionService())// UPDATE: Inisialisasi Upload Controller// servicesProvider.ProvideUploadService() sekarang sudah return Pointer (*), jadi aman.uploadController := controllers.NewUploadController(servicesProvider.ProvideUploadService())return &controllerProvider{academyController: academyController,accountDetailController: accountDetailController,authenticationController: authenticationController,emailVerificationController: emailVerificationController,eventController: eventController,examController: examController,forgotPasswordController: forgotPasswordController,optionController: optionController,regionController: regionController,uploadController: uploadController, // Pointer assign ke Pointer}}// --- Getter Methods ---func (c *controllerProvider) ProvideAcademyController() controllers.AcademyController {return c.academyController}func (c *controllerProvider) ProvideAccountDetailController() controllers.AccountDetailController {return c.accountDetailController}func (c *controllerProvider) ProvideAuthenticationController() controllers.AuthenticationController {return c.authenticationController}func (c *controllerProvider) ProvideEmailVerificationController() controllers.EmailVerificationController {return c.emailVerificationController}func (c *controllerProvider) ProvideEventController() controllers.EventController {return c.eventController}func (c *controllerProvider) ProvideExamController() controllers.ExamController {return c.examController}func (c *controllerProvider) ProvideForgotPasswordController() controllers.ForgotPasswordController {return c.forgotPasswordController}func (c *controllerProvider) ProvideOptionController() controllers.OptionController {return c.optionController}func (c *controllerProvider) ProvideRegionController() controllers.RegionController {return c.regionController}// UPDATE: Return Pointer (*)func (c *controllerProvider) ProvideUploadController() *controllers.UploadController {return c.uploadController}
123456789101112131415161718192021222324252627282930package providerimport "abdanhafidz.com/go-boilerplate/middleware"type MiddlewareProvider interface {ProvideAuthenticationMiddleware() middleware.AuthenticationMiddlewareProvideAuthorizationMiddleware() middleware.AuthorizationMiddleware}type middlewareProvider struct {authenticationMiddleware middleware.AuthenticationMiddlewareauthorizationMiddleware middleware.AuthorizationMiddleware}func NewMiddlewareProvider(servicesProvider ServicesProvider) MiddlewareProvider {authenticationMiddleware := middleware.NewAuthenticationMiddleware(servicesProvider.ProvideJWTService())authorizationMiddleware := middleware.NewAuthorizationMiddleware(servicesProvider.ProvideEventService())return &middlewareProvider{authenticationMiddleware: authenticationMiddleware,authorizationMiddleware: authorizationMiddleware,}}func (p *middlewareProvider) ProvideAuthenticationMiddleware() middleware.AuthenticationMiddleware {return p.authenticationMiddleware}func (p *middlewareProvider) ProvideAuthorizationMiddleware() middleware.AuthorizationMiddleware {return p.authorizationMiddleware}123456789101112131415161718192021222324252627282930package providerimport "abdanhafidz.com/go-boilerplate/middleware"type MiddlewareProvider interface {ProvideAuthenticationMiddleware() middleware.AuthenticationMiddlewareProvideAuthorizationMiddleware() middleware.AuthorizationMiddleware}type middlewareProvider struct {authenticationMiddleware middleware.AuthenticationMiddlewareauthorizationMiddleware middleware.AuthorizationMiddleware}func NewMiddlewareProvider(servicesProvider ServicesProvider) MiddlewareProvider {authenticationMiddleware := middleware.NewAuthenticationMiddleware(servicesProvider.ProvideJWTService())authorizationMiddleware := middleware.NewAuthorizationMiddleware(servicesProvider.ProvideEventService())return &middlewareProvider{authenticationMiddleware: authenticationMiddleware,authorizationMiddleware: authorizationMiddleware,}}func (p *middlewareProvider) ProvideAuthenticationMiddleware() middleware.AuthenticationMiddleware {return p.authenticationMiddleware}func (p *middlewareProvider) ProvideAuthorizationMiddleware() middleware.AuthorizationMiddleware {return p.authorizationMiddleware}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868712 unmodified lines100101102103package providerimport (entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/gin-gonic/gin")type AppProvider interface {ProvideRouter() *gin.EngineProvideConfig() ConfigProviderProvideRepositories() RepositoriesProviderProvideServices() ServicesProviderProvideControllers() ControllerProviderProvideMiddlewares() MiddlewareProvider}type appProvider struct {ginRouter *gin.EngineconfigProvider ConfigProviderrepositoriesProvider RepositoriesProviderservicesProvider ServicesProvidercontrollerProvider ControllerProvidermiddlewareProvider MiddlewareProvider}func NewAppProvider() AppProvider {ginRouter := gin.Default()configProvider := NewConfigProvider()repositoriesProvider := NewRepositoriesProvider(configProvider)servicesProvider := NewServicesProvider(repositoriesProvider, configProvider)controllerProvider := NewControllerProvider(servicesProvider)middlewareProvider := NewMiddlewareProvider(servicesProvider)configProvider.ProvideDatabaseConfig().AutoMigrateAll(// Accounts & Auth&entity.Account{},&entity.AccountDetail{},&entity.EmailVerification{},&entity.ExternalAuth{},&entity.FCM{},&entity.ForgotPassword{},// Events&entity.Events{},&entity.EventAssign{},&entity.Announcement{},// Problemset & Exam&entity.ProblemSet{},&entity.Questions{},&entity.Exam{},&entity.ProblemSetExamAssign{},&entity.ExamEventAssign{},// Exam Attempt & Result&entity.ExamEventAnswer{},&entity.ExamEventAttempt{},&entity.Result{},// Academy LMS&entity.Academy{},&entity.AcademyMaterial{},&entity.AcademyContent{},&entity.AcademyMaterialProgress{},&entity.AcademyContentProgress{},&entity.AcademyProgress{},// Options & Regions&entity.OptionCategory{},&entity.OptionValues{},&entity.RegionProvince{},&entity.RegionCity{},)return &appProvider{ginRouter: ginRouter,configProvider: configProvider,repositoriesProvider: repositoriesProvider,servicesProvider: servicesProvider,controllerProvider: controllerProvider,middlewareProvider: middlewareProvider,}}func (a *appProvider) ProvideRouter() *gin.Engine {return a.ginRouter}func (a *appProvider) ProvideConfig() ConfigProvider {return a.configProvider}12 unmodified linesfunc (a *appProvider) ProvideMiddlewares() MiddlewareProvider {return a.middlewareProvider}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110212 unmodified lines115116117118package providerimport ("log"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/gin-gonic/gin")type AppProvider interface {ProvideRouter() *gin.EngineProvideConfig() ConfigProviderProvideRepositories() RepositoriesProviderProvideServices() ServicesProviderProvideControllers() ControllerProviderProvideMiddlewares() MiddlewareProvider}type appProvider struct {ginRouter *gin.EngineconfigProvider ConfigProviderrepositoriesProvider RepositoriesProviderservicesProvider ServicesProvidercontrollerProvider ControllerProvidermiddlewareProvider MiddlewareProvider}func NewAppProvider() AppProvider {ginRouter := gin.Default()configProvider := NewConfigProvider()repositoriesProvider := NewRepositoriesProvider(configProvider)supabaseCfg := configProvider.ProvideSupabaseConfig()storageDriver := NewSupabaseStorage(supabaseCfg.URL, supabaseCfg.ServiceKey, supabaseCfg.BucketName)servicesProvider := NewServicesProvider(repositoriesProvider, configProvider, storageDriver)controllerProvider := NewControllerProvider(servicesProvider)middlewareProvider := NewMiddlewareProvider(servicesProvider)// Database Migrations with error handlingerr := configProvider.ProvideDatabaseConfig().AutoMigrateAll(// Accounts & Auth&entity.Account{},&entity.AccountDetail{},&entity.EmailVerification{},&entity.ExternalAuth{},&entity.FCM{},&entity.ForgotPassword{},// Events&entity.Events{},&entity.EventAssign{},&entity.Announcement{},// Problemset & Exam&entity.ProblemSet{},&entity.Questions{},&entity.Exam{},&entity.ProblemSetExamAssign{},&entity.ExamEventAssign{},// Exam Attempt & Result&entity.ExamEventAnswer{},&entity.ExamEventAttempt{},&entity.Result{},// Academy LMS&entity.Academy{},&entity.AcademyMaterial{},&entity.AcademyContent{},&entity.AcademyMaterialProgress{},&entity.AcademyContentProgress{},&entity.AcademyProgress{},// Options & Regions&entity.OptionCategory{},&entity.OptionValues{},&entity.RegionProvince{},&entity.RegionCity{},// Files Storage&entity.File{},)if err != nil {log.Fatalf("Database migration failed: %v", err)}return &appProvider{ginRouter: ginRouter,configProvider: configProvider,repositoriesProvider: repositoriesProvider,servicesProvider: servicesProvider,controllerProvider: controllerProvider,middlewareProvider: middlewareProvider,}}func (a *appProvider) ProvideRouter() *gin.Engine {return a.ginRouter}func (a *appProvider) ProvideConfig() ConfigProvider {return a.configProvider}12 unmodified linesfunc (a *appProvider) ProvideMiddlewares() MiddlewareProvider {return a.middlewareProvider}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170package providerimport "abdanhafidz.com/go-boilerplate/repositories"type RepositoriesProvider interface {ProvideAcademyRepository() repositories.AcademyRepositoryProvideAccountDetailRepository() repositories.AccountDetailRepositoryProvideAccountRepository() repositories.AccountRepositoryProvideEmailVerificationRepository() repositories.EmailVerificationRepositoryProvideEventAssignRepository() repositories.EventAssignRepositoryProvideEventsRepository() repositories.EventsRepositoryProvideExamEventAnswerRepository() repositories.ExamEventAnswerRepositoryProvideExamEventAssignRepository() repositories.ExamEventAssignRepositoryProvideExamEventAttemptRepository() repositories.ExamEventAttemptRepositoryProvideExamRepository() repositories.ExamRepositoryProvideExternalAuthRepository() repositories.ExternalAuthRepositoryProvideFCMRepository() repositories.FCMRepositoryProvideForgotPasswordRepository() repositories.ForgotPasswordRepositoryProvideOptionRepository() repositories.OptionRepositoryProvideProblemSetExamAssignRepository() repositories.ProblemSetExamAssignRepositoryProvideProblemSetRepository() repositories.ProblemSetRepositoryProvideQuestionsRepository() repositories.QuestionsRepositoryProvideRegionRepository() repositories.RegionRepositoryProvideResultRepository() repositories.ResultRepository}type repositoriesProvider struct {academyRepository repositories.AcademyRepositoryaccountDetailRepository repositories.AccountDetailRepositoryaccountRepository repositories.AccountRepositoryemailVerificationRepository repositories.EmailVerificationRepositoryeventAssignRepository repositories.EventAssignRepositoryeventsRepository repositories.EventsRepositoryexamEventAnswerRepository repositories.ExamEventAnswerRepositoryexamEventAssignRepository repositories.ExamEventAssignRepositoryexamEventAttemptRepository repositories.ExamEventAttemptRepositoryexamRepository repositories.ExamRepositoryexternalAuthRepository repositories.ExternalAuthRepositoryfCMRepository repositories.FCMRepositoryforgotPasswordRepository repositories.ForgotPasswordRepositoryoptionRepository repositories.OptionRepositoryproblemSetExamAssignRepository repositories.ProblemSetExamAssignRepositoryproblemSetRepository repositories.ProblemSetRepositoryquestionsRepository repositories.QuestionsRepositoryregionRepository repositories.RegionRepositoryresultRepository repositories.ResultRepository}func NewRepositoriesProvider(cfg ConfigProvider) RepositoriesProvider {dbConfig := cfg.ProvideDatabaseConfig()db := dbConfig.GetInstance()academyRepository := repositories.NewAcademyRepository(db)accountDetailRepository := repositories.NewAccountDetailRepository(db)accountRepository := repositories.NewAccountRepository(db)emailVerificationRepository := repositories.NewEmailVerificationRepository(db)eventAssignRepository := repositories.NewEventAssignRepository(db)eventsRepository := repositories.NewEventsRepository(db)examEventAnswerRepository := repositories.NewExamEventAnswerRepository(db)examEventAssignRepository := repositories.NewExamEventAssignRepository(db)examEventAttemptRepository := repositories.NewExamEventAttemptRepository(db)examRepository := repositories.NewExamRepository(db)externalAuthRepository := repositories.NewExternalAuthRepository(db)fCMRepository := repositories.NewFCMRepository(db)forgotPasswordRepository := repositories.NewForgotPasswordRepository(db)optionRepository := repositories.NewOptionRepository(db)problemSetExamAssignRepository := repositories.NewProblemSetExamAssignRepository(db)problemSetRepository := repositories.NewProblemSetRepository(db)questionsRepository := repositories.NewQuestionsRepository(db)regionRepository := repositories.NewRegionRepository(db)resultRepository := repositories.NewResultRepository(db)return &repositoriesProvider{academyRepository: academyRepository,accountDetailRepository: accountDetailRepository,accountRepository: accountRepository,emailVerificationRepository: emailVerificationRepository,eventAssignRepository: eventAssignRepository,eventsRepository: eventsRepository,examEventAnswerRepository: examEventAnswerRepository,examEventAssignRepository: examEventAssignRepository,examEventAttemptRepository: examEventAttemptRepository,examRepository: examRepository,externalAuthRepository: externalAuthRepository,fCMRepository: fCMRepository,forgotPasswordRepository: forgotPasswordRepository,optionRepository: optionRepository,problemSetExamAssignRepository: problemSetExamAssignRepository,problemSetRepository: problemSetRepository,questionsRepository: questionsRepository,regionRepository: regionRepository,resultRepository: resultRepository,}}func (r *repositoriesProvider) ProvideAcademyRepository() repositories.AcademyRepository {return r.academyRepository}func (r *repositoriesProvider) ProvideAccountDetailRepository() repositories.AccountDetailRepository {return r.accountDetailRepository}func (r *repositoriesProvider) ProvideAccountRepository() repositories.AccountRepository {return r.accountRepository}func (r *repositoriesProvider) ProvideEmailVerificationRepository() repositories.EmailVerificationRepository {return r.emailVerificationRepository}func (r *repositoriesProvider) ProvideEventAssignRepository() repositories.EventAssignRepository {return r.eventAssignRepository}func (r *repositoriesProvider) ProvideEventsRepository() repositories.EventsRepository {return r.eventsRepository}func (r *repositoriesProvider) ProvideExamEventAnswerRepository() repositories.ExamEventAnswerRepository {return r.examEventAnswerRepository}func (r *repositoriesProvider) ProvideExamEventAssignRepository() repositories.ExamEventAssignRepository {return r.examEventAssignRepository}func (r *repositoriesProvider) ProvideExamEventAttemptRepository() repositories.ExamEventAttemptRepository {return r.examEventAttemptRepository}func (r *repositoriesProvider) ProvideExamRepository() repositories.ExamRepository {return r.examRepository}func (r *repositoriesProvider) ProvideExternalAuthRepository() repositories.ExternalAuthRepository {return r.externalAuthRepository}func (r *repositoriesProvider) ProvideFCMRepository() repositories.FCMRepository {return r.fCMRepository}func (r *repositoriesProvider) ProvideForgotPasswordRepository() repositories.ForgotPasswordRepository {return r.forgotPasswordRepository}func (r *repositoriesProvider) ProvideOptionRepository() repositories.OptionRepository {return r.optionRepository}func (r *repositoriesProvider) ProvideProblemSetExamAssignRepository() repositories.ProblemSetExamAssignRepository {return r.problemSetExamAssignRepository}func (r *repositoriesProvider) ProvideProblemSetRepository() repositories.ProblemSetRepository {return r.problemSetRepository}func (r *repositoriesProvider) ProvideQuestionsRepository() repositories.QuestionsRepository {return r.questionsRepository}func (r *repositoriesProvider) ProvideRegionRepository() repositories.RegionRepository {return r.regionRepository}func (r *repositoriesProvider) ProvideResultRepository() repositories.ResultRepository {return r.resultRepository}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178package providerimport "abdanhafidz.com/go-boilerplate/repositories"type RepositoriesProvider interface {ProvideAcademyRepository() repositories.AcademyRepositoryProvideAccountDetailRepository() repositories.AccountDetailRepositoryProvideAccountRepository() repositories.AccountRepositoryProvideEmailVerificationRepository() repositories.EmailVerificationRepositoryProvideEventAssignRepository() repositories.EventAssignRepositoryProvideEventsRepository() repositories.EventsRepositoryProvideExamEventAnswerRepository() repositories.ExamEventAnswerRepositoryProvideExamEventAssignRepository() repositories.ExamEventAssignRepositoryProvideExamEventAttemptRepository() repositories.ExamEventAttemptRepositoryProvideExamRepository() repositories.ExamRepositoryProvideExternalAuthRepository() repositories.ExternalAuthRepositoryProvideFCMRepository() repositories.FCMRepositoryProvideForgotPasswordRepository() repositories.ForgotPasswordRepositoryProvideOptionRepository() repositories.OptionRepositoryProvideProblemSetExamAssignRepository() repositories.ProblemSetExamAssignRepositoryProvideProblemSetRepository() repositories.ProblemSetRepositoryProvideQuestionsRepository() repositories.QuestionsRepositoryProvideRegionRepository() repositories.RegionRepositoryProvideResultRepository() repositories.ResultRepositoryProvideFileRepository() repositories.FileRepository}type repositoriesProvider struct {academyRepository repositories.AcademyRepositoryaccountDetailRepository repositories.AccountDetailRepositoryaccountRepository repositories.AccountRepositoryemailVerificationRepository repositories.EmailVerificationRepositoryeventAssignRepository repositories.EventAssignRepositoryeventsRepository repositories.EventsRepositoryexamEventAnswerRepository repositories.ExamEventAnswerRepositoryexamEventAssignRepository repositories.ExamEventAssignRepositoryexamEventAttemptRepository repositories.ExamEventAttemptRepositoryexamRepository repositories.ExamRepositoryexternalAuthRepository repositories.ExternalAuthRepositoryfCMRepository repositories.FCMRepositoryforgotPasswordRepository repositories.ForgotPasswordRepositoryoptionRepository repositories.OptionRepositoryproblemSetExamAssignRepository repositories.ProblemSetExamAssignRepositoryproblemSetRepository repositories.ProblemSetRepositoryquestionsRepository repositories.QuestionsRepositoryregionRepository repositories.RegionRepositoryresultRepository repositories.ResultRepositoryfileRepository repositories.FileRepository // Added field}func NewRepositoriesProvider(cfg ConfigProvider) RepositoriesProvider {dbConfig := cfg.ProvideDatabaseConfig()db := dbConfig.GetInstance()academyRepository := repositories.NewAcademyRepository(db)accountDetailRepository := repositories.NewAccountDetailRepository(db)accountRepository := repositories.NewAccountRepository(db)emailVerificationRepository := repositories.NewEmailVerificationRepository(db)eventAssignRepository := repositories.NewEventAssignRepository(db)eventsRepository := repositories.NewEventsRepository(db)examEventAnswerRepository := repositories.NewExamEventAnswerRepository(db)examEventAssignRepository := repositories.NewExamEventAssignRepository(db)examEventAttemptRepository := repositories.NewExamEventAttemptRepository(db)examRepository := repositories.NewExamRepository(db)externalAuthRepository := repositories.NewExternalAuthRepository(db)fCMRepository := repositories.NewFCMRepository(db)forgotPasswordRepository := repositories.NewForgotPasswordRepository(db)optionRepository := repositories.NewOptionRepository(db)problemSetExamAssignRepository := repositories.NewProblemSetExamAssignRepository(db)problemSetRepository := repositories.NewProblemSetRepository(db)questionsRepository := repositories.NewQuestionsRepository(db)regionRepository := repositories.NewRegionRepository(db)resultRepository := repositories.NewResultRepository(db)fileRepository := repositories.NewFileRepository(db) // Init herereturn &repositoriesProvider{academyRepository: academyRepository,accountDetailRepository: accountDetailRepository,accountRepository: accountRepository,emailVerificationRepository: emailVerificationRepository,eventAssignRepository: eventAssignRepository,eventsRepository: eventsRepository,examEventAnswerRepository: examEventAnswerRepository,examEventAssignRepository: examEventAssignRepository,examEventAttemptRepository: examEventAttemptRepository,examRepository: examRepository,externalAuthRepository: externalAuthRepository,fCMRepository: fCMRepository,forgotPasswordRepository: forgotPasswordRepository,optionRepository: optionRepository,problemSetExamAssignRepository: problemSetExamAssignRepository,problemSetRepository: problemSetRepository,questionsRepository: questionsRepository,regionRepository: regionRepository,resultRepository: resultRepository,fileRepository: fileRepository, // Assign here}}func (r *repositoriesProvider) ProvideAcademyRepository() repositories.AcademyRepository {return r.academyRepository}func (r *repositoriesProvider) ProvideAccountDetailRepository() repositories.AccountDetailRepository {return r.accountDetailRepository}func (r *repositoriesProvider) ProvideAccountRepository() repositories.AccountRepository {return r.accountRepository}func (r *repositoriesProvider) ProvideEmailVerificationRepository() repositories.EmailVerificationRepository {return r.emailVerificationRepository}func (r *repositoriesProvider) ProvideEventAssignRepository() repositories.EventAssignRepository {return r.eventAssignRepository}func (r *repositoriesProvider) ProvideEventsRepository() repositories.EventsRepository {return r.eventsRepository}func (r *repositoriesProvider) ProvideExamEventAnswerRepository() repositories.ExamEventAnswerRepository {return r.examEventAnswerRepository}func (r *repositoriesProvider) ProvideExamEventAssignRepository() repositories.ExamEventAssignRepository {return r.examEventAssignRepository}func (r *repositoriesProvider) ProvideExamEventAttemptRepository() repositories.ExamEventAttemptRepository {return r.examEventAttemptRepository}func (r *repositoriesProvider) ProvideExamRepository() repositories.ExamRepository {return r.examRepository}func (r *repositoriesProvider) ProvideExternalAuthRepository() repositories.ExternalAuthRepository {return r.externalAuthRepository}func (r *repositoriesProvider) ProvideFCMRepository() repositories.FCMRepository {return r.fCMRepository}func (r *repositoriesProvider) ProvideForgotPasswordRepository() repositories.ForgotPasswordRepository {return r.forgotPasswordRepository}func (r *repositoriesProvider) ProvideOptionRepository() repositories.OptionRepository {return r.optionRepository}func (r *repositoriesProvider) ProvideProblemSetExamAssignRepository() repositories.ProblemSetExamAssignRepository {return r.problemSetExamAssignRepository}func (r *repositoriesProvider) ProvideProblemSetRepository() repositories.ProblemSetRepository {return r.problemSetRepository}func (r *repositoriesProvider) ProvideQuestionsRepository() repositories.QuestionsRepository {return r.questionsRepository}func (r *repositoriesProvider) ProvideRegionRepository() repositories.RegionRepository {return r.regionRepository}func (r *repositoriesProvider) ProvideResultRepository() repositories.ResultRepository {return r.resultRepository}func (r *repositoriesProvider) ProvideFileRepository() repositories.FileRepository {return r.fileRepository}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103package providerimport "abdanhafidz.com/go-boilerplate/services"type ServicesProvider interface {ProvideEventService() services.EventServiceProvideAcademyService() services.AcademyServiceProvideProblemSetService() services.ProblemSetServiceProvideJWTService() services.JWTServiceProvideRegionService() services.RegionServiceProvideOptionService() services.OptionServiceProvideExamService() services.ExamServiceProvideAccountService() services.AccountServiceProvideForgotPasswordService() services.ForgotPasswordServiceProvideEmailVerificationService() services.EmailVerificationServiceProvideExternalAuthService() services.ExternalAuthService}type servicesProvider struct {eventService services.EventServiceacademyService services.AcademyServiceproblemSetService services.ProblemSetServicejWTService services.JWTServiceregionService services.RegionServiceoptionService services.OptionServiceexamService services.ExamServiceaccountService services.AccountServiceforgotPasswordService services.ForgotPasswordServiceemailVerificationService services.EmailVerificationServiceexternalAuthService services.ExternalAuthService}func NewServicesProvider(repoProvider RepositoriesProvider, configProvider ConfigProvider) ServicesProvider {eventService := services.NewEventService(repoProvider.ProvideEventsRepository(), repoProvider.ProvideEventAssignRepository())academyService := services.NewAcademyService(repoProvider.ProvideAcademyRepository())problemSetService := services.NewProblemSetService(repoProvider.ProvideProblemSetRepository(), repoProvider.ProvideQuestionsRepository(), repoProvider.ProvideProblemSetExamAssignRepository())jWTService := services.NewJWTService(configProvider.ProvideJWTConfig().GetSecretKey())regionService := services.NewRegionService(repoProvider.ProvideRegionRepository())optionService := services.NewOptionService(repoProvider.ProvideOptionRepository())examService := services.NewExamService(eventService, problemSetService, repoProvider.ProvideProblemSetExamAssignRepository(), repoProvider.ProvideExamRepository(), repoProvider.ProvideExamEventAttemptRepository(), repoProvider.ProvideExamEventAssignRepository(), repoProvider.ProvideExamEventAnswerRepository(), repoProvider.ProvideResultRepository())accountService := services.NewAccountService(jWTService, repoProvider.ProvideAccountRepository(), repoProvider.ProvideAccountDetailRepository())forgotPasswordService := services.NewForgotPasswordService(jWTService, repoProvider.ProvideAccountRepository(), repoProvider.ProvideForgotPasswordRepository())emailVerificationService := services.NewEmailVerificationService(accountService, repoProvider.ProvideEmailVerificationRepository())externalAuthService := services.NewExternalAuthService(jWTService, accountService, repoProvider.ProvideExternalAuthRepository())return &servicesProvider{eventService: eventService,academyService: academyService,problemSetService: problemSetService,jWTService: jWTService,regionService: regionService,optionService: optionService,examService: examService,accountService: accountService,forgotPasswordService: forgotPasswordService,emailVerificationService: emailVerificationService,externalAuthService: externalAuthService,}}func (s *servicesProvider) ProvideEventService() services.EventService {return s.eventService}func (s *servicesProvider) ProvideAcademyService() services.AcademyService {return s.academyService}func (s *servicesProvider) ProvideProblemSetService() services.ProblemSetService {return s.problemSetService}func (s *servicesProvider) ProvideJWTService() services.JWTService {return s.jWTService}func (s *servicesProvider) ProvideRegionService() services.RegionService {return s.regionService}func (s *servicesProvider) ProvideOptionService() services.OptionService {return s.optionService}func (s *servicesProvider) ProvideExamService() services.ExamService {return s.examService}func (s *servicesProvider) ProvideAccountService() services.AccountService {return s.accountService}func (s *servicesProvider) ProvideForgotPasswordService() services.ForgotPasswordService {return s.forgotPasswordService}func (s *servicesProvider) ProvideEmailVerificationService() services.EmailVerificationService {return s.emailVerificationService}func (s *servicesProvider) ProvideExternalAuthService() services.ExternalAuthService {return s.externalAuthService}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121package providerimport (// Pastikan path ini sesuai dengan go.mod kamu (misal: quzuu-backend-v2/services)"abdanhafidz.com/go-boilerplate/services")type ServicesProvider interface {ProvideEventService() services.EventServiceProvideAcademyService() services.AcademyServiceProvideProblemSetService() services.ProblemSetServiceProvideJWTService() services.JWTServiceProvideRegionService() services.RegionServiceProvideOptionService() services.OptionServiceProvideExamService() services.ExamServiceProvideAccountService() services.AccountServiceProvideForgotPasswordService() services.ForgotPasswordServiceProvideEmailVerificationService() services.EmailVerificationServiceProvideExternalAuthService() services.ExternalAuthService// UPDATE: Mengembalikan pointer karena UploadService adalah struct, bukan interfaceProvideUploadService() *services.UploadService}type servicesProvider struct {eventService services.EventServiceacademyService services.AcademyServiceproblemSetService services.ProblemSetServicejWTService services.JWTServiceregionService services.RegionServiceoptionService services.OptionServiceexamService services.ExamServiceaccountService services.AccountServiceforgotPasswordService services.ForgotPasswordServiceemailVerificationService services.EmailVerificationServiceexternalAuthService services.ExternalAuthService// Field untuk menyimpan instance UploadServiceuploadService *services.UploadService}func NewServicesProvider(repoProvider RepositoriesProvider,configProvider ConfigProvider,storageProvider services.StorageProvider, // Didapat dari main/wire) ServicesProvider {// Inisialisasi service lain...eventService := services.NewEventService(repoProvider.ProvideEventsRepository(), repoProvider.ProvideEventAssignRepository())academyService := services.NewAcademyService(repoProvider.ProvideAcademyRepository())problemSetService := services.NewProblemSetService(repoProvider.ProvideProblemSetRepository(), repoProvider.ProvideQuestionsRepository(), repoProvider.ProvideProblemSetExamAssignRepository())jWTService := services.NewJWTService(configProvider.ProvideJWTConfig().GetSecretKey())regionService := services.NewRegionService(repoProvider.ProvideRegionRepository())optionService := services.NewOptionService(repoProvider.ProvideOptionRepository())examService := services.NewExamService(eventService, problemSetService, repoProvider.ProvideProblemSetExamAssignRepository(), repoProvider.ProvideExamRepository(), repoProvider.ProvideExamEventAttemptRepository(), repoProvider.ProvideExamEventAssignRepository(), repoProvider.ProvideExamEventAnswerRepository(), repoProvider.ProvideResultRepository())accountService := services.NewAccountService(jWTService, repoProvider.ProvideAccountRepository(), repoProvider.ProvideAccountDetailRepository())forgotPasswordService := services.NewForgotPasswordService(jWTService, repoProvider.ProvideAccountRepository(), repoProvider.ProvideForgotPasswordRepository())emailVerificationService := services.NewEmailVerificationService(accountService, repoProvider.ProvideEmailVerificationRepository())externalAuthService := services.NewExternalAuthService(jWTService, accountService, repoProvider.ProvideExternalAuthRepository())uploadService := services.NewUploadService(storageProvider,repoProvider.ProvideFileRepository(),)return &servicesProvider{eventService: eventService,academyService: academyService,problemSetService: problemSetService,jWTService: jWTService,regionService: regionService,optionService: optionService,examService: examService,accountService: accountService,forgotPasswordService: forgotPasswordService,emailVerificationService: emailVerificationService,externalAuthService: externalAuthService,uploadService: uploadService,}}// ... (Getter method lainnya tetap sama) ...func (s *servicesProvider) ProvideEventService() services.EventService {return s.eventService}func (s *servicesProvider) ProvideAcademyService() services.AcademyService {return s.academyService}func (s *servicesProvider) ProvideProblemSetService() services.ProblemSetService {return s.problemSetService}func (s *servicesProvider) ProvideJWTService() services.JWTService {return s.jWTService}func (s *servicesProvider) ProvideRegionService() services.RegionService {return s.regionService}func (s *servicesProvider) ProvideOptionService() services.OptionService {return s.optionService}func (s *servicesProvider) ProvideExamService() services.ExamService {return s.examService}func (s *servicesProvider) ProvideAccountService() services.AccountService {return s.accountService}func (s *servicesProvider) ProvideForgotPasswordService() services.ForgotPasswordService {return s.forgotPasswordService}func (s *servicesProvider) ProvideEmailVerificationService() services.EmailVerificationService {return s.emailVerificationService}func (s *servicesProvider) ProvideExternalAuthService() services.ExternalAuthService {return s.externalAuthService}func (s *servicesProvider) ProvideUploadService() *services.UploadService {return s.uploadService}
12345678910111213package provider
import ( "context" "mime/multipart")
// StorageProvider defines the behavior for file operationstype StorageProvider interface { UploadFile(ctx context.Context, file multipart.File, header *multipart.FileHeader) (string, error) GetFileURL(path string) (string, error) DeleteFile(path string) error}123456789101112131415161718192021222324252627282930313233343536373839404142package provider
import ( "context" "fmt" "io"
// Pastikan import library supabase client yang Anda pakai benar storage_go "github.com/supabase-community/storage-go" )
type SupabaseStorage struct { client *storage_go.Client bucketName string url string}
func NewSupabaseStorage(url string, key string, bucketName string) *SupabaseStorage { client := storage_go.NewClient(url+"/storage/v1", key, nil) return &SupabaseStorage{ client: client, bucketName: bucketName, url: url, }}
func (s *SupabaseStorage) UploadFile(ctx context.Context, file io.Reader, destinationPath string, contentType string) (string, error) { _, err := s.client.UploadFile(s.bucketName, destinationPath, file, storage_go.FileOptions{ ContentType: &contentType, Upsert: new(bool), // Use new(bool) to create a pointer to false })
if err != nil { return "", err } publicURL := s.client.GetPublicUrl(s.bucketName, destinationPath).SignedURL if publicURL == "" { publicURL = fmt.Sprintf("%s/storage/v1/object/public/%s/%s", s.url, s.bucketName, destinationPath) }
return publicURL, nil}6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061622 unmodified lines656667686970717273747576777879807 unmodified lines88899091929394959697989910010110210310410510610710810911011 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571586 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961973 unmodified lines2012022032042052062074 unmodified lines2122132142152162172182191 unmodified line22122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025111 unmodified lines2632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503511 unmodified line3533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963976 unmodified linesentity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type AcademyRepository interface {// AcademyGetAcademyByID(ctx context.Context, id uuid.UUID) (entity.Academy, error)GetAcademyBySlug(ctx context.Context, slug string) (entity.Academy, error)GetAcademyWithProgress(ctx context.Context, accountId uuid.UUID, slug string) (entity.Academy, error)CreateAcademy(ctx context.Context, a entity.Academy) (entity.Academy, error)UpdateAcademy(ctx context.Context, a entity.Academy) (entity.Academy, error)DeleteAcademy(ctx context.Context, id uuid.UUID) errorListAcademy(ctx context.Context, accountId uuid.UUID) ([]entity.Academy, error)GetAcademyWithMaterials(ctx context.Context, id uuid.UUID) (entity.Academy, []entity.AcademyMaterial, error)CountMaterialsByAcademyID(ctx context.Context, academyId uuid.UUID) (int64, error)// MaterialGetMaterialBySlug(ctx context.Context, academy_id uuid.UUID, materialSlug string) (entity.AcademyMaterial, error)GetMaterialByID(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, error)GetMaterialWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, slug string) (entity.AcademyMaterial, error)CreateMaterial(ctx context.Context, m entity.AcademyMaterial) (entity.AcademyMaterial, error)UpdateMaterial(ctx context.Context, m entity.AcademyMaterial) (entity.AcademyMaterial, error)DeleteMaterial(ctx context.Context, id uuid.UUID) errorListMaterials(ctx context.Context, academyId uuid.UUID) ([]entity.AcademyMaterial, error)GetMaterialWithContents(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, []entity.AcademyContent, error)// ContentGetContentBySlug(ctx context.Context, materialId uuid.UUID, order uint) (entity.AcademyContent, error)GetContentByID(ctx context.Context, id uuid.UUID) (entity.AcademyContent, error)GetContentWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID,materialId uuid.UUID, order uint) (entity.AcademyContent, error)CreateContent(ctx context.Context, c entity.AcademyContent) (entity.AcademyContent, error)UpdateContent(ctx context.Context, c entity.AcademyContent) (entity.AcademyContent, error)DeleteContent(ctx context.Context, id uuid.UUID) errorCountContentsByMaterialID(ctx context.Context, materialId uuid.UUID) (int64, error)// ProgressGetAcademyProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (entity.AcademyProgress, error)GetMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID) (entity.AcademyMaterialProgress, error)GetContentProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID, contentId uuid.UUID) (entity.AcademyContentProgress, error)UpsertAcademyProgress(ctx context.Context, p entity.AcademyProgress) (entity.AcademyProgress, error)UpsertMaterialProgress(ctx context.Context, p entity.AcademyMaterialProgress) (entity.AcademyMaterialProgress, error)UpsertContentProgress(ctx context.Context, p entity.AcademyContentProgress) (entity.AcademyContentProgress, error)CountCompletedContentsByMaterialAndAccount(ctx context.Context, accountId uuid.UUID, materialId uuid.UUID) (int64, error)CountCompletedMaterialsByAcademyAndAccount(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (int64, error)}type academyRepository struct{ db *gorm.DB }2 unmodified linesreturn &academyRepository{db: db}}// ========== ACADEMY ==========func (r *academyRepository) GetAcademyWithMaterials(ctx context.Context, id uuid.UUID) (entity.Academy, []entity.AcademyMaterial, error) {var a entity.Academyerr := r.db.WithContext(ctx).First(&a, "id = ?", id).Errorif err != nil {return entity.Academy{}, nil, err}var m []entity.AcademyMaterialreturn a, m, r.db.WithContext(ctx).Where("academy_id = ?", id).Find(&m).Error}func (r *academyRepository) GetAcademyByID(ctx context.Context, id uuid.UUID) (entity.Academy, error) {7 unmodified lines}func (r *academyRepository) GetAcademyWithProgress(ctx context.Context, accountId uuid.UUID, slug string) (entity.Academy, error) {var a entity.Academyvar err errora, err = r.GetAcademyBySlug(ctx, slug)if err != nil {return a, err}academyId := a.Idvar ap entity.AcademyProgressap, err = r.GetAcademyProgress(ctx, accountId, academyId)if err != nil && err != gorm.ErrRecordNotFound {return a, err}a.AcademyProgresss = apreturn a, nil}11 unmodified linesfunc (r *academyRepository) ListAcademy(ctx context.Context, accountId uuid.UUID) ([]entity.Academy, error) {var list []entity.Academyif err := r.db.WithContext(ctx).Find(&list).Error; err != nil {return nil, err}for i := range list {academyId := list[i].Idap, err := r.GetAcademyProgress(ctx, accountId, academyId)if err != nil && err != gorm.ErrRecordNotFound {return nil, err}list[i].AcademyProgresss = ap}return list, nil}func (r *academyRepository) CountMaterialsByAcademyID(ctx context.Context, academyId uuid.UUID) (int64, error) {var count int64query := r.db.WithContext(ctx).Where("academy_id = ?", academyId)err := query.Model(&entity.AcademyMaterial{}).Count(&count).Errorreturn count, err}// ========== MATERIAL ==========func (r *academyRepository) GetMaterialByID(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, error) {var m entity.AcademyMaterialreturn m, r.db.WithContext(ctx).First(&m, "id = ?", id).Error6 unmodified linesfunc (r *academyRepository) GetMaterialWithContents(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, []entity.AcademyContent, error) {var m entity.AcademyMaterialerr := r.db.WithContext(ctx).First(&m, "id = ?", id).Errorif err != nil {return entity.AcademyMaterial{}, nil, err}var c []entity.AcademyContentreturn m, c, r.db.WithContext(ctx).Where("material_id = ?", id).Order("order asc").Find(&c).Error}func (r *academyRepository) GetMaterialWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, slug string) (entity.AcademyMaterial, error){var m entity.AcademyMaterialvar err errorm, err = r.GetMaterialBySlug(ctx, academyId, slug)if err != nil {return m, err}MaterialId := m.Idvar ap entity.AcademyMaterialProgressap, err = r.GetMaterialProgress(ctx, accountId,academyId, MaterialId)if err != nil && err != gorm.ErrRecordNotFound {return m, err}m.AcademyMaterialProgress = apreturn m, nil}3 unmodified linesfunc (r *academyRepository) ListMaterials(ctx context.Context, academyId uuid.UUID) ([]entity.AcademyMaterial, error) {var list []entity.AcademyMaterialreturn list, r.db.WithContext(ctx).Where("academy_id = ?", academyId).Find(&list).Error}func (r *academyRepository) UpdateMaterial(ctx context.Context, m entity.AcademyMaterial) (entity.AcademyMaterial, error) {4 unmodified linesreturn r.db.WithContext(ctx).Delete(&entity.AcademyMaterial{}, "id = ?", id).Error}// ========== CONTENT ==========func (r *academyRepository) GetContentByID(ctx context.Context, id uuid.UUID) (entity.AcademyContent, error) {var c entity.AcademyContentreturn c, r.db.WithContext(ctx).First(&c, "id = ?", id).Error1 unmodified linefunc (r *academyRepository) GetContentBySlug(ctx context.Context, materialId uuid.UUID, order uint) (entity.AcademyContent, error) {var c entity.AcademyContentresult := r.db.WithContext(ctx).// Escape "order" with backslashes and double quotes: \"order\"Where("\"order\" = ?", order).Where("material_id = ?", materialId).First(&c)return c, result.Error}func (r *academyRepository) GetContentWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID,materialId uuid.UUID, order uint) (entity.AcademyContent, error){var c entity.AcademyContentvar err errorc, err = r.GetContentBySlug(ctx,materialId,order)if err != nil {return c, err}var ap entity.AcademyContentProgressap, err = r.GetContentProgress(ctx, accountId, academyId, materialId,c.Id)if err != nil && err != gorm.ErrRecordNotFound {return c, err}c.AcademyContentProgress = apreturn c, nil}11 unmodified linesfunc (r *academyRepository) CountContentsByMaterialID(ctx context.Context, materialId uuid.UUID) (int64, error) {var count int64query := r.db.WithContext(ctx).Where("material_id = ?", materialId)err := query.Model(&entity.AcademyContent{}).Count(&count).Errorreturn count, err}// ========== PROGRESS ==========func (r *academyRepository) GetAcademyProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (entity.AcademyProgress, error) {var existing entity.AcademyProgresserr := r.db.WithContext(ctx).Where("account_id = ? AND academy_id = ?", accountId, academyId).First(&existing).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return entity.AcademyProgress{AccountId: accountId,AcademyId: academyId,Status: "NOT_STARTED",Progress: 0,TotalCompletedMaterials: 0,}, nil}if err != nil {return existing, err}return existing, nil}func (r *academyRepository) UpsertAcademyProgress(ctx context.Context, p entity.AcademyProgress) (entity.AcademyProgress, error) {var existing entity.AcademyProgresserr := r.db.WithContext(ctx).First(&existing, "account_id = ? AND academy_id = ?", p.AccountId, p.AcademyId).Errorif err == gorm.ErrRecordNotFound {return p, r.db.WithContext(ctx).Create(&p).Error}return p, r.db.WithContext(ctx).Model(&existing).Updates(p).Error}func (r *academyRepository) GetMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID) (entity.AcademyMaterialProgress, error) {var existing entity.AcademyMaterialProgresserr := r.db.WithContext(ctx).First(&existing, "account_id = ? AND academy_id = ? AND material_id = ?", accountId, academyId, materialId).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return entity.AcademyMaterialProgress{AccountId: accountId,AcademyId: academyId,MaterialId: materialId,Progress: 0,TotalCompletedContents: 0,Status: "NOT_STARTED",}, nil}if err != nil {return existing, err}return existing, nil}func (r *academyRepository) UpsertMaterialProgress(ctx context.Context, p entity.AcademyMaterialProgress) (entity.AcademyMaterialProgress, error) {var existing entity.AcademyMaterialProgresserr := r.db.WithContext(ctx).First(&existing, "account_id = ? AND academy_id = ? AND material_id = ?", p.AccountId, p.AcademyId, p.MaterialId).Errorif err == gorm.ErrRecordNotFound {return p, r.db.WithContext(ctx).Create(&p).Error}return p, r.db.WithContext(ctx).Model(&existing).Updates(p).Error}func (r *academyRepository) GetContentProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID, contentId uuid.UUID) (entity.AcademyContentProgress, error) {var existing entity.AcademyContentProgresserr := r.db.WithContext(ctx).First(&existing, "account_id = ? AND academy_id = ? AND material_id = ? AND content_id = ?", accountId, academyId, materialId,contentId).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return entity.AcademyContentProgress{1 unmodified lineAcademyId: academyId,MaterialId: materialId,ContentId: contentId,Status: "NOT_STARTED",}, nil}if err != nil {return existing, err}return existing, nil}func (r *academyRepository) UpsertContentProgress(ctx context.Context, p entity.AcademyContentProgress) (entity.AcademyContentProgress, error) {var existing entity.AcademyContentProgresserr := r.db.WithContext(ctx).First(&existing, "account_id = ? AND academy_id = ? AND material_id = ? AND content_id = ?", p.AccountId, p.AcademyId, p.MaterialId, p.ContentId).Errorif err == gorm.ErrRecordNotFound {return p, r.db.WithContext(ctx).Create(&p).Error}return p, r.db.WithContext(ctx).Model(&existing).Updates(p).Error}// UTILSfunc (r *academyRepository) CountCompletedContentsByMaterialAndAccount(ctx context.Context, accountId uuid.UUID, materialId uuid.UUID) (int64, error) {var count int64query := r.db.WithContext(ctx).Where("account_id = ? AND material_id = ? AND status = ?", accountId, materialId, "COMPLETED")err := query.Model(&entity.AcademyContentProgress{}).Count(&count).Errorreturn count, err}func (r *academyRepository) CountCompletedMaterialsByAcademyAndAccount(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (int64, error) {var count int64query := r.db.WithContext(ctx).Where("account_id = ? AND academy_id = ? AND status = ?", accountId, academyId, "COMPLETED")err := query.Model(&entity.AcademyMaterialProgress{}).Count(&count).Errorreturn count, err}6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263642 unmodified lines6768697071727374757677787980818283848586877 unmodified lines959697989910010110210310410510610710810911 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701716 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002013 unmodified lines2052062072082092102114 unmodified lines2162172182192202211 unmodified line22322422522622722822923023123223323423523623723823924024124211 unmodified lines2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083091 unmodified line3113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714726 unmodified linesentity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm""gorm.io/gorm/clause")type AcademyRepository interface {Atomic(ctx context.Context, fn func(r AcademyRepository) error) errorGetAcademyByID(ctx context.Context, id uuid.UUID) (entity.Academy, error)GetAcademyBySlug(ctx context.Context, slug string) (entity.Academy, error)GetAcademyWithProgress(ctx context.Context, accountId uuid.UUID, slug string) (entity.Academy, error)CreateAcademy(ctx context.Context, a entity.Academy) (entity.Academy, error)UpdateAcademy(ctx context.Context, a entity.Academy) (entity.Academy, error)DeleteAcademy(ctx context.Context, id uuid.UUID) errorListAcademy(ctx context.Context, accountId uuid.UUID) ([]entity.Academy, error)GetAcademyWithMaterials(ctx context.Context, id uuid.UUID) (entity.Academy, []entity.AcademyMaterial, error)CountMaterialsByAcademyID(ctx context.Context, academyId uuid.UUID) (int64, error)GetMaterialBySlug(ctx context.Context, academy_id uuid.UUID, materialSlug string) (entity.AcademyMaterial, error)GetMaterialByID(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, error)GetMaterialWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, slug string) (entity.AcademyMaterial, error)CreateMaterial(ctx context.Context, m entity.AcademyMaterial) (entity.AcademyMaterial, error)UpdateMaterial(ctx context.Context, m entity.AcademyMaterial) (entity.AcademyMaterial, error)DeleteMaterial(ctx context.Context, id uuid.UUID) errorListMaterials(ctx context.Context, academyId uuid.UUID) ([]entity.AcademyMaterial, error)GetMaterialWithContents(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, []entity.AcademyContent, error)GetContentBySlug(ctx context.Context, materialId uuid.UUID, order uint) (entity.AcademyContent, error)GetContentByID(ctx context.Context, id uuid.UUID) (entity.AcademyContent, error)GetContentWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID, order uint) (entity.AcademyContent, error)CreateContent(ctx context.Context, c entity.AcademyContent) (entity.AcademyContent, error)UpdateContent(ctx context.Context, c entity.AcademyContent) (entity.AcademyContent, error)DeleteContent(ctx context.Context, id uuid.UUID) errorCountContentsByMaterialID(ctx context.Context, materialId uuid.UUID) (int64, error)GetAcademyProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (entity.AcademyProgress, error)GetMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID) (entity.AcademyMaterialProgress, error)GetContentProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID, contentId uuid.UUID) (entity.AcademyContentProgress, error)UpsertAcademyProgress(ctx context.Context, p entity.AcademyProgress) (entity.AcademyProgress, error)UpsertMaterialProgress(ctx context.Context, p entity.AcademyMaterialProgress) (entity.AcademyMaterialProgress, error)UpsertContentProgress(ctx context.Context, p entity.AcademyContentProgress) (entity.AcademyContentProgress, error)DeleteContentProgressByContentID(ctx context.Context, contentId uuid.UUID) errorDeleteContentProgressByMaterialID(ctx context.Context, materialId uuid.UUID) errorDeleteMaterialProgressByMaterialID(ctx context.Context, materialId uuid.UUID) errorCountCompletedContentsByMaterialAndAccount(ctx context.Context, accountId uuid.UUID, materialId uuid.UUID) (int64, error)CountCompletedMaterialsByAcademyAndAccount(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (int64, error)CountStartedMaterialsByAcademyAndAccount(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (int64, error)DecrementMaterialOrdersGreaterThan(ctx context.Context, academyId uuid.UUID, order uint) errorDecrementContentOrdersGreaterThan(ctx context.Context, materialId uuid.UUID, order uint) errorGetAccumulatedMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (float64, error)BatchRecalculateMaterialProgress(ctx context.Context, materialId uuid.UUID) errorBatchRecalculateAcademyProgress(ctx context.Context, academyId uuid.UUID) error}type academyRepository struct{ db *gorm.DB }2 unmodified linesreturn &academyRepository{db: db}}func (r *academyRepository) Atomic(ctx context.Context, fn func(r AcademyRepository) error) error {return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {txRepo := NewAcademyRepository(tx)return fn(txRepo)})}func (r *academyRepository) GetAcademyWithMaterials(ctx context.Context, id uuid.UUID) (entity.Academy, []entity.AcademyMaterial, error) {var a entity.Academyif err := r.db.WithContext(ctx).First(&a, "id = ?", id).Error; err != nil {return entity.Academy{}, nil, err}var m []entity.AcademyMaterialerr := r.db.WithContext(ctx).Where("academy_id = ?", id).Order("\"order\" ASC").Find(&m).Errorreturn a, m, err}func (r *academyRepository) GetAcademyByID(ctx context.Context, id uuid.UUID) (entity.Academy, error) {7 unmodified lines}func (r *academyRepository) GetAcademyWithProgress(ctx context.Context, accountId uuid.UUID, slug string) (entity.Academy, error) {a, err := r.GetAcademyBySlug(ctx, slug)if err != nil {return a, err}ap, err := r.GetAcademyProgress(ctx, accountId, a.Id)if err != nil {return a, err}a.AcademyProgresss = apreturn a, nil}11 unmodified linesfunc (r *academyRepository) ListAcademy(ctx context.Context, accountId uuid.UUID) ([]entity.Academy, error) {var list []entity.Academyif err := r.db.WithContext(ctx).Find(&list).Error; err != nil {return nil, err}if len(list) == 0 {return list, nil}academyIDs := make([]uuid.UUID, len(list))for i, ac := range list {academyIDs[i] = ac.Id}var progressList []entity.AcademyProgressif err := r.db.WithContext(ctx).Where("account_id = ?", accountId).Where("academy_id IN ?", academyIDs).Find(&progressList).Error; err != nil {return nil, err}progressMap := make(map[uuid.UUID]entity.AcademyProgress)for _, p := range progressList {progressMap[p.AcademyId] = p}for i := range list {if p, exists := progressMap[list[i].Id]; exists {list[i].AcademyProgresss = p} else {list[i].AcademyProgresss = entity.AcademyProgress{AccountId: accountId,AcademyId: list[i].Id,Status: entity.StatusNotStarted,}}}return list, nil}func (r *academyRepository) CountMaterialsByAcademyID(ctx context.Context, academyId uuid.UUID) (int64, error) {var count int64err := r.db.WithContext(ctx).Model(&entity.AcademyMaterial{}).Where("academy_id = ?", academyId).Count(&count).Errorreturn count, err}func (r *academyRepository) GetMaterialByID(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, error) {var m entity.AcademyMaterialreturn m, r.db.WithContext(ctx).First(&m, "id = ?", id).Error6 unmodified linesfunc (r *academyRepository) GetMaterialWithContents(ctx context.Context, id uuid.UUID) (entity.AcademyMaterial, []entity.AcademyContent, error) {var m entity.AcademyMaterialif err := r.db.WithContext(ctx).First(&m, "id = ?", id).Error; err != nil {return entity.AcademyMaterial{}, nil, err}var c []entity.AcademyContenterr := r.db.WithContext(ctx).Where("material_id = ?", id).Order("\"order\" ASC").Find(&c).Errorreturn m, c, err}func (r *academyRepository) GetMaterialWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, slug string) (entity.AcademyMaterial, error) {m, err := r.GetMaterialBySlug(ctx, academyId, slug)if err != nil {return m, err}ap, err := r.GetMaterialProgress(ctx, accountId, academyId, m.Id)if err != nil {return m, err}m.AcademyMaterialProgress = apreturn m, nil}3 unmodified linesfunc (r *academyRepository) ListMaterials(ctx context.Context, academyId uuid.UUID) ([]entity.AcademyMaterial, error) {var list []entity.AcademyMaterialreturn list, r.db.WithContext(ctx).Where("academy_id = ?", academyId).Order("\"order\" ASC").Find(&list).Error}func (r *academyRepository) UpdateMaterial(ctx context.Context, m entity.AcademyMaterial) (entity.AcademyMaterial, error) {4 unmodified linesreturn r.db.WithContext(ctx).Delete(&entity.AcademyMaterial{}, "id = ?", id).Error}func (r *academyRepository) GetContentByID(ctx context.Context, id uuid.UUID) (entity.AcademyContent, error) {var c entity.AcademyContentreturn c, r.db.WithContext(ctx).First(&c, "id = ?", id).Error1 unmodified linefunc (r *academyRepository) GetContentBySlug(ctx context.Context, materialId uuid.UUID, order uint) (entity.AcademyContent, error) {var c entity.AcademyContenterr := r.db.WithContext(ctx).Where("\"order\" = ? AND material_id = ?", order, materialId).First(&c).Errorreturn c, err}func (r *academyRepository) GetContentWithProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID, order uint) (entity.AcademyContent, error) {c, err := r.GetContentBySlug(ctx, materialId, order)if err != nil {return c, err}ap, err := r.GetContentProgress(ctx, accountId, academyId, materialId, c.Id)if err != nil {return c, err}c.AcademyContentProgress = apreturn c, nil}11 unmodified linesfunc (r *academyRepository) CountContentsByMaterialID(ctx context.Context, materialId uuid.UUID) (int64, error) {var count int64err := r.db.WithContext(ctx).Model(&entity.AcademyContent{}).Where("material_id = ?", materialId).Count(&count).Errorreturn count, err}func (r *academyRepository) GetAcademyProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (entity.AcademyProgress, error) {var existing entity.AcademyProgresserr := r.db.WithContext(ctx).Where("account_id = ? AND academy_id = ?", accountId, academyId).First(&existing).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return entity.AcademyProgress{AccountId: accountId,AcademyId: academyId,Status: entity.StatusNotStarted,}, nil}return existing, err}func (r *academyRepository) UpsertAcademyProgress(ctx context.Context, p entity.AcademyProgress) (entity.AcademyProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}},UpdateAll: true,}).Save(&p).Error}func (r *academyRepository) GetMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID) (entity.AcademyMaterialProgress, error) {var existing entity.AcademyMaterialProgresserr := r.db.WithContext(ctx).Where("account_id = ? AND material_id = ?", accountId, materialId).First(&existing).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return entity.AcademyMaterialProgress{AccountId: accountId,AcademyId: academyId,MaterialId: materialId,Status: entity.StatusNotStarted,}, nil}return existing, err}func (r *academyRepository) UpsertMaterialProgress(ctx context.Context, p entity.AcademyMaterialProgress) (entity.AcademyMaterialProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}},UpdateAll: true,}).Save(&p).Error}func (r *academyRepository) GetContentProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialId uuid.UUID, contentId uuid.UUID) (entity.AcademyContentProgress, error) {var existing entity.AcademyContentProgresserr := r.db.WithContext(ctx).Where("account_id = ? AND content_id = ?", accountId, contentId).First(&existing).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return entity.AcademyContentProgress{1 unmodified lineAcademyId: academyId,MaterialId: materialId,ContentId: contentId,Status: entity.StatusNotStarted,}, nil}return existing, err}func (r *academyRepository) UpsertContentProgress(ctx context.Context, p entity.AcademyContentProgress) (entity.AcademyContentProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}},UpdateAll: true,}).Save(&p).Error}func (r *academyRepository) DeleteContentProgressByContentID(ctx context.Context, contentId uuid.UUID) error {return r.db.WithContext(ctx).Where("content_id = ?", contentId).Delete(&entity.AcademyContentProgress{}).Error}func (r *academyRepository) DeleteContentProgressByMaterialID(ctx context.Context, materialId uuid.UUID) error {return r.db.WithContext(ctx).Where("material_id = ?", materialId).Delete(&entity.AcademyContentProgress{}).Error}func (r *academyRepository) DeleteMaterialProgressByMaterialID(ctx context.Context, materialId uuid.UUID) error {return r.db.WithContext(ctx).Where("material_id = ?", materialId).Delete(&entity.AcademyMaterialProgress{}).Error}func (r *academyRepository) CountCompletedContentsByMaterialAndAccount(ctx context.Context, accountId uuid.UUID, materialId uuid.UUID) (int64, error) {var count int64err := r.db.WithContext(ctx).Model(&entity.AcademyContentProgress{}).Where("account_id = ? AND material_id = ? AND status = ?", accountId, materialId, entity.StatusCompleted).Count(&count).Errorreturn count, err}func (r *academyRepository) CountCompletedMaterialsByAcademyAndAccount(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (int64, error) {var count int64err := r.db.WithContext(ctx).Model(&entity.AcademyMaterialProgress{}).Where("account_id = ? AND academy_id = ? AND status = ?", accountId, academyId, entity.StatusCompleted).Count(&count).Errorreturn count, err}func (r *academyRepository) CountStartedMaterialsByAcademyAndAccount(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (int64, error) {var count int64err := r.db.WithContext(ctx).Model(&entity.AcademyMaterialProgress{}).Where("account_id = ? AND academy_id = ? AND status IN ?", accountId, academyId, []string{entity.StatusInProgress, entity.StatusCompleted}).Count(&count).Errorreturn count, err}func (r *academyRepository) DecrementMaterialOrdersGreaterThan(ctx context.Context, academyId uuid.UUID, order uint) error {return r.db.WithContext(ctx).Model(&entity.AcademyMaterial{}).Where("academy_id = ? AND \"order\" > ?", academyId, order).Update("\"order\"", gorm.Expr("\"order\" - 1")).Error}func (r *academyRepository) DecrementContentOrdersGreaterThan(ctx context.Context, materialId uuid.UUID, order uint) error {return r.db.WithContext(ctx).Model(&entity.AcademyContent{}).Where("material_id = ? AND \"order\" > ?", materialId, order).Update("\"order\"", gorm.Expr("\"order\" - 1")).Error}func (r *academyRepository) GetAccumulatedMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (float64, error) {var total float64err := r.db.WithContext(ctx).Model(&entity.AcademyMaterialProgress{}).Where("account_id = ? AND academy_id = ?", accountId, academyId).Select("COALESCE(SUM(progress), 0)").Scan(&total).Errorreturn total, err}func (r *academyRepository) BatchRecalculateMaterialProgress(ctx context.Context, materialId uuid.UUID) error {totalContents, err := r.CountContentsByMaterialID(ctx, materialId)if err != nil {return err}if totalContents == 0 {return r.db.WithContext(ctx).Model(&entity.AcademyMaterialProgress{}).Where("material_id = ?", materialId).Updates(map[string]interface{}{"progress": 100,"status": entity.StatusCompleted,"total_completed_contents": 0,}).Error}return r.db.WithContext(ctx).Exec(`UPDATE academy_material_progresses ampSETtotal_completed_contents = (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED'),progress = (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED')::float / ? * 100,status = CASEWHEN (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED') >= ? THEN 'COMPLETED'ELSE 'IN_PROGRESS'END,completed_at = CASEWHEN (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED') >= ? THEN NOW()ELSE NULLENDWHERE amp.material_id = ?`, totalContents, totalContents, totalContents, materialId).Error}func (r *academyRepository) BatchRecalculateAcademyProgress(ctx context.Context, academyId uuid.UUID) error {totalMaterials, err := r.CountMaterialsByAcademyID(ctx, academyId)if err != nil {return err}if totalMaterials == 0 {return r.db.WithContext(ctx).Model(&entity.AcademyProgress{}).Where("academy_id = ?", academyId).Updates(map[string]interface{}{"progress": 100,"status": entity.StatusCompleted,"total_completed_materials": 0,}).Error}return r.db.WithContext(ctx).Exec(`UPDATE academy_progress apSETprogress = (SELECT COALESCE(SUM(amp.progress), 0) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id)::float / ?,total_completed_materials = (SELECT COUNT(id) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED'),status = CASEWHEN (SELECT COUNT(id) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED') >= ? THEN 'COMPLETED'ELSE 'IN_PROGRESS'END,completed_at = CASEWHEN (SELECT COUNT(id) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED') >= ? THEN NOW()ELSE NULLENDWHERE ap.academy_id = ?`, totalMaterials, totalMaterials, totalMaterials, academyId).Error}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamEventAnswerRepository interface {Create(ctx context.Context, ans *entity.ExamEventAnswer) errorUpdate(ctx context.Context, ans *entity.ExamEventAnswer) errorGetByAttemptAndQuestion(ctx context.Context, attemptId uuid.UUID, questionId uuid.UUID) (entity.ExamEventAnswer, error)ListByAttempt(ctx context.Context, attemptId uuid.UUID) ([]entity.ExamEventAnswer, error)DeleteByAttempt(ctx context.Context, attemptId uuid.UUID) error// decomposed result (answer + question)}type examEventAnswerRepository struct {db *gorm.DB}func NewExamEventAnswerRepository(db *gorm.DB) ExamEventAnswerRepository {return &examEventAnswerRepository{db: db}}func (r *examEventAnswerRepository) Create(ctx context.Context, ans *entity.ExamEventAnswer) error {return r.db.WithContext(ctx).Create(ans).Error}func (r *examEventAnswerRepository) Update(ctx context.Context, ans *entity.ExamEventAnswer) error {return r.db.WithContext(ctx).Where("attempt_id = ? AND question_id = ?", ans.AttemptId, ans.QuestionId).Updates(ans).Error}func (r *examEventAnswerRepository) GetByAttemptAndQuestion(ctx context.Context, attemptId uuid.UUID, questionId uuid.UUID) (entity.ExamEventAnswer, error) {var ans entity.ExamEventAnswererr := r.db.WithContext(ctx).Where("attempt_id = ? AND question_id = ?", attemptId, questionId).First(&ans).Errorreturn ans, err}func (r *examEventAnswerRepository) ListByAttempt(ctx context.Context, attemptId uuid.UUID) ([]entity.ExamEventAnswer, error) {var answers []entity.ExamEventAnswererr := r.db.WithContext(ctx).Where("attempt_id = ?", attemptId).Find(&answers).Errorreturn answers, err}func (r *examEventAnswerRepository) DeleteByAttempt(ctx context.Context, attemptId uuid.UUID) error {return r.db.WithContext(ctx).Where("attempt_id = ?", attemptId).Delete(&entity.ExamEventAnswer{}).Error}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamEventAnswerRepository interface {Create(ctx context.Context, ans *entity.ExamEventAnswer) errorUpdate(ctx context.Context, ans *entity.ExamEventAnswer) errorGetByAttemptAndQuestion(ctx context.Context, attemptId uuid.UUID, questionId uuid.UUID) (entity.ExamEventAnswer, error)ListByAttempt(ctx context.Context, attemptId uuid.UUID) ([]entity.ExamEventAnswer, error)DeleteByAttempt(ctx context.Context, attemptId uuid.UUID) error// decomposed result (answer + question)}type examEventAnswerRepository struct {db *gorm.DB}func NewExamEventAnswerRepository(db *gorm.DB) ExamEventAnswerRepository {return &examEventAnswerRepository{db: db}}func (r *examEventAnswerRepository) Create(ctx context.Context, ans *entity.ExamEventAnswer) error {return r.db.WithContext(ctx).Create(ans).Error}func (r *examEventAnswerRepository) Update(ctx context.Context, ans *entity.ExamEventAnswer) error {return r.db.WithContext(ctx).Where("attempt_id = ? AND question_id = ?", ans.AttemptId, ans.QuestionId).Updates(ans).Error}func (r *examEventAnswerRepository) GetByAttemptAndQuestion(ctx context.Context, attemptId uuid.UUID, questionId uuid.UUID) (entity.ExamEventAnswer, error) {var ans entity.ExamEventAnswererr := r.db.WithContext(ctx).Where("attempt_id = ? AND question_id = ?", attemptId, questionId).First(&ans).Errorreturn ans, err}func (r *examEventAnswerRepository) ListByAttempt(ctx context.Context, attemptId uuid.UUID) ([]entity.ExamEventAnswer, error) {var answers []entity.ExamEventAnswererr := r.db.WithContext(ctx).Where("attempt_id = ?", attemptId).Find(&answers).Errorreturn answers, err}func (r *examEventAnswerRepository) DeleteByAttempt(ctx context.Context, attemptId uuid.UUID) error {return r.db.WithContext(ctx).Where("attempt_id = ?", attemptId).Delete(&entity.ExamEventAnswer{}).Error}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamEventAssignRepository interface {Create(ctx context.Context, m entity.ExamEventAssign) errorListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.ExamEventAssign, error)Delete(ctx context.Context, id uuid.UUID) errorCheck(ctx context.Context, eventId uuid.UUID, examId uuid.UUID) error}type examEventAssignRepository struct{ db *gorm.DB }func NewExamEventAssignRepository(db *gorm.DB) ExamEventAssignRepository {return &examEventAssignRepository{db}}func (r *examEventAssignRepository) Check(ctx context.Context, eventId uuid.UUID, examId uuid.UUID) error {return r.db.WithContext(ctx).Where("event_id = ?", eventId).Where("exam_id = ?", examId).First(&entity.ExamEventAssign{}).Error}func (r *examEventAssignRepository) Create(ctx context.Context, m entity.ExamEventAssign) error {return r.db.WithContext(ctx).Create(&m).Error}func (r *examEventAssignRepository) ListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.ExamEventAssign, error) {var items []entity.ExamEventAssignerr := r.db.WithContext(ctx).Where("event_id = ?", eventId).Preload("Exam").Find(&items).Errorreturn items, err}func (r *examEventAssignRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.ExamEventAssign{}).Error}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamEventAssignRepository interface {Create(ctx context.Context, m entity.ExamEventAssign) errorListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.ExamEventAssign, error)Delete(ctx context.Context, id uuid.UUID) errorCheck(ctx context.Context, eventId uuid.UUID, examId uuid.UUID) error}type examEventAssignRepository struct{ db *gorm.DB }func NewExamEventAssignRepository(db *gorm.DB) ExamEventAssignRepository {return &examEventAssignRepository{db}}func (r *examEventAssignRepository) Check(ctx context.Context, eventId uuid.UUID, examId uuid.UUID) error {return r.db.WithContext(ctx).Where("event_id = ?", eventId).Where("exam_id = ?", examId).First(&entity.ExamEventAssign{}).Error}func (r *examEventAssignRepository) Create(ctx context.Context, m entity.ExamEventAssign) error {return r.db.WithContext(ctx).Create(&m).Error}func (r *examEventAssignRepository) ListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.ExamEventAssign, error) {var items []entity.ExamEventAssignerr := r.db.WithContext(ctx).Where("event_id = ?", eventId).Preload("Exam").Find(&items).Errorreturn items, err}func (r *examEventAssignRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.ExamEventAssign{}).Error}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamEventAttemptRepository interface {Create(ctx context.Context, a *entity.ExamEventAttempt) errorGetById(ctx context.Context, attemptId uuid.UUID) (entity.ExamEventAttempt, error)GetByExamEvent(ctx context.Context, eventId uuid.UUID, examId uuid.UUID, accountId uuid.UUID) (entity.ExamEventAttempt, error)Update(ctx context.Context, a *entity.ExamEventAttempt) error}type examEventAttemptRepository struct{ db *gorm.DB }func NewExamEventAttemptRepository(db *gorm.DB) ExamEventAttemptRepository {return &examEventAttemptRepository{db}}func (r *examEventAttemptRepository) Create(ctx context.Context, a *entity.ExamEventAttempt) error {return r.db.WithContext(ctx).Create(a).Error}func (r *examEventAttemptRepository) GetById(ctx context.Context, attemptId uuid.UUID) (entity.ExamEventAttempt, error) {var a entity.ExamEventAttempterr := r.db.WithContext(ctx).Preload("Answers").First(&a, "id = ?", attemptId).Errorreturn a, err}func (r *examEventAttemptRepository) GetByExamEvent(ctx context.Context, eventId uuid.UUID, examId uuid.UUID, accountId uuid.UUID) (entity.ExamEventAttempt, error) {var attempt entity.ExamEventAttempterr := r.db.WithContext(ctx).Preload("Answers").Where("event_id = ?", eventId).Where("exam_id = ?", examId).Where("account_id = ?", accountId).First(&attempt).Errorreturn attempt, err}func (r *examEventAttemptRepository) Update(ctx context.Context, a *entity.ExamEventAttempt) error {return r.db.WithContext(ctx).Model(&entity.ExamEventAttempt{}).Where("id = ?", a.Id).Updates(a).Error}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamEventAttemptRepository interface {Create(ctx context.Context, a *entity.ExamEventAttempt) errorGetById(ctx context.Context, attemptId uuid.UUID) (entity.ExamEventAttempt, error)GetByExamEvent(ctx context.Context, eventId uuid.UUID, examId uuid.UUID, accountId uuid.UUID) (entity.ExamEventAttempt, error)Update(ctx context.Context, a *entity.ExamEventAttempt) error}type examEventAttemptRepository struct{ db *gorm.DB }func NewExamEventAttemptRepository(db *gorm.DB) ExamEventAttemptRepository {return &examEventAttemptRepository{db}}func (r *examEventAttemptRepository) Create(ctx context.Context, a *entity.ExamEventAttempt) error {return r.db.WithContext(ctx).Create(a).Error}func (r *examEventAttemptRepository) GetById(ctx context.Context, attemptId uuid.UUID) (entity.ExamEventAttempt, error) {var a entity.ExamEventAttempterr := r.db.WithContext(ctx).Preload("Answers").First(&a, "id = ?", attemptId).Errorreturn a, err}func (r *examEventAttemptRepository) GetByExamEvent(ctx context.Context, eventId uuid.UUID, examId uuid.UUID, accountId uuid.UUID) (entity.ExamEventAttempt, error) {var attempt entity.ExamEventAttempterr := r.db.WithContext(ctx).Preload("Answers").Where("event_id = ?", eventId).Where("exam_id = ?", examId).Where("account_id = ?", accountId).First(&attempt).Errorreturn attempt, err}func (r *examEventAttemptRepository) Update(ctx context.Context, a *entity.ExamEventAttempt) error {return r.db.WithContext(ctx).Model(&entity.ExamEventAttempt{}).Where("id = ?", a.Id).Updates(a).Error}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamRepository interface {Create(ctx context.Context, e entity.Exam) errorGet(ctx context.Context, id uuid.UUID) (entity.Exam, error)GetBySlug(ctx context.Context, slug string) (entity.Exam, error)Update(ctx context.Context, e entity.Exam) errorDelete(ctx context.Context, id uuid.UUID) errorList(ctx context.Context) ([]entity.Exam, error)// Additional business needListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Exam, error)}type examRepository struct {db *gorm.DB}func NewExamRepository(db *gorm.DB) ExamRepository {return &examRepository{db}}// ================= CRUD =================func (r *examRepository) Create(ctx context.Context, e entity.Exam) error {return r.db.WithContext(ctx).Create(&e).Error}func (r *examRepository) Get(ctx context.Context, id uuid.UUID) (entity.Exam, error) {var e entity.Examerr := r.db.WithContext(ctx).First(&e, "exam_id = ?", id).Errorreturn e, err}func (r *examRepository) GetBySlug(ctx context.Context, slug string) (entity.Exam, error) {var e entity.Examerr := r.db.WithContext(ctx).Where("slug = ?", slug).First(&e).Errorreturn e, err}func (r *examRepository) Update(ctx context.Context, e entity.Exam) error {return r.db.WithContext(ctx).Model(&entity.Exam{}).Where("exam_id = ?", e.Id).Updates(e).Error}func (r *examRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("exam_id = ?", id).Delete(&entity.Exam{}).Error}func (r *examRepository) List(ctx context.Context) ([]entity.Exam, error) {var list []entity.Examerr := r.db.WithContext(ctx).Order("created_at DESC").Find(&list).Errorreturn list, err}// =========== Business Specific ============func (r *examRepository) ListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Exam, error) {var exams []entity.Examerr := r.db.WithContext(ctx).Table("exam").Joins(`JOIN exam_event_assign ON exam_event_assign.exam_id = exam.id`).Where("exam_event_assign.event_id = ?", eventId).Find(&exams).Errorreturn exams, err}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ExamRepository interface {Create(ctx context.Context, e entity.Exam) errorGet(ctx context.Context, id uuid.UUID) (entity.Exam, error)GetBySlug(ctx context.Context, slug string) (entity.Exam, error)Update(ctx context.Context, e entity.Exam) errorDelete(ctx context.Context, id uuid.UUID) errorList(ctx context.Context) ([]entity.Exam, error)// Additional business needListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Exam, error)}type examRepository struct {db *gorm.DB}func NewExamRepository(db *gorm.DB) ExamRepository {return &examRepository{db}}// ================= CRUD =================func (r *examRepository) Create(ctx context.Context, e entity.Exam) error {return r.db.WithContext(ctx).Create(&e).Error}func (r *examRepository) Get(ctx context.Context, id uuid.UUID) (entity.Exam, error) {var e entity.Examerr := r.db.WithContext(ctx).First(&e, "exam_id = ?", id).Errorreturn e, err}func (r *examRepository) GetBySlug(ctx context.Context, slug string) (entity.Exam, error) {var e entity.Examerr := r.db.WithContext(ctx).Where("slug = ?", slug).First(&e).Errorreturn e, err}func (r *examRepository) Update(ctx context.Context, e entity.Exam) error {return r.db.WithContext(ctx).Model(&entity.Exam{}).Where("exam_id = ?", e.Id).Updates(e).Error}func (r *examRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("exam_id = ?", id).Delete(&entity.Exam{}).Error}func (r *examRepository) List(ctx context.Context) ([]entity.Exam, error) {var list []entity.Examerr := r.db.WithContext(ctx).Order("created_at DESC").Find(&list).Errorreturn list, err}// =========== Business Specific ============func (r *examRepository) ListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Exam, error) {var exams []entity.Examerr := r.db.WithContext(ctx).Table("exam").Joins(`JOIN exam_event_assign ON exam_event_assign.exam_id = exam.id`).Where("exam_event_assign.event_id = ?", eventId).Find(&exams).Errorreturn exams, err}
12345678910111213141516171819202122232425262728293031323334353637383940414243package repositories
import ( "context" "errors"
"github.com/google/uuid" "gorm.io/gorm"
entity "abdanhafidz.com/go-boilerplate/models/entity" http_error "abdanhafidz.com/go-boilerplate/models/error")
type FileRepository interface { Create(ctx context.Context, file *entity.File) error FindByID(ctx context.Context, id uuid.UUID) (*entity.File, error)}
type fileRepository struct { db *gorm.DB}
func NewFileRepository(db *gorm.DB) FileRepository { return &fileRepository{db: db}}
func (r *fileRepository) Create(ctx context.Context, file *entity.File) error { return r.db.WithContext(ctx).Create(file).Error}
func (r *fileRepository) FindByID(ctx context.Context, id uuid.UUID) (*entity.File, error) { var file entity.File result := r.db.WithContext(ctx).First(&file, "id = ?", id)
if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, http_error.NOT_FOUND_ERROR } return nil, result.Error }
return &file, nil}12345678910111213141516171819202122232425262728293031323334353637383940package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ProblemSetExamAssignRepository interface {Create(ctx context.Context, m entity.ProblemSetExamAssign) errorGetByExam(ctx context.Context, examId uuid.UUID) (entity.ProblemSetExamAssign, error)Delete(ctx context.Context, id uuid.UUID) error}type problemSetExamAssignRepository struct{ db *gorm.DB }func NewProblemSetExamAssignRepository(db *gorm.DB) ProblemSetExamAssignRepository {return &problemSetExamAssignRepository{db}}func (r *problemSetExamAssignRepository) Create(ctx context.Context, m entity.ProblemSetExamAssign) error {return r.db.WithContext(ctx).Create(&m).Error}func (r *problemSetExamAssignRepository) GetByExam(ctx context.Context, examId uuid.UUID) (entity.ProblemSetExamAssign, error) {var items entity.ProblemSetExamAssignerr := r.db.WithContext(ctx).Where("exam_id = ?", examId).Preload("ProblemSet").First(&items).Errorreturn items, err}func (r *problemSetExamAssignRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.ProblemSetExamAssign{}).Error}12345678910111213141516171819202122232425262728293031323334353637383940package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ProblemSetExamAssignRepository interface {Create(ctx context.Context, m entity.ProblemSetExamAssign) errorGetByExam(ctx context.Context, examId uuid.UUID) (entity.ProblemSetExamAssign, error)Delete(ctx context.Context, id uuid.UUID) error}type problemSetExamAssignRepository struct{ db *gorm.DB }func NewProblemSetExamAssignRepository(db *gorm.DB) ProblemSetExamAssignRepository {return &problemSetExamAssignRepository{db}}func (r *problemSetExamAssignRepository) Create(ctx context.Context, m entity.ProblemSetExamAssign) error {return r.db.WithContext(ctx).Create(&m).Error}func (r *problemSetExamAssignRepository) GetByExam(ctx context.Context, examId uuid.UUID) (entity.ProblemSetExamAssign, error) {var items entity.ProblemSetExamAssignerr := r.db.WithContext(ctx).Where("exam_id = ?", examId).Preload("ProblemSet").First(&items).Errorreturn items, err}func (r *problemSetExamAssignRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.ProblemSetExamAssign{}).Error}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ProblemSetRepository interface {Create(ctx context.Context, ps entity.ProblemSet) errorGet(ctx context.Context, id uuid.UUID) (entity.ProblemSet, error)Update(ctx context.Context, ps entity.ProblemSet) errorDelete(ctx context.Context, id uuid.UUID) errorList(ctx context.Context) ([]entity.ProblemSet, error)}type problemSetRepository struct {db *gorm.DB}func NewProblemSetRepository(db *gorm.DB) ProblemSetRepository {return &problemSetRepository{db: db}}func (r *problemSetRepository) Create(ctx context.Context, ps entity.ProblemSet) error {return r.db.WithContext(ctx).Create(&ps).Error}func (r *problemSetRepository) Get(ctx context.Context, id uuid.UUID) (entity.ProblemSet, error) {var ps entity.ProblemSeterr := r.db.WithContext(ctx).First(&ps, "id = ?", id).Errorreturn ps, err}func (r *problemSetRepository) List(ctx context.Context) ([]entity.ProblemSet, error) {var list []entity.ProblemSeterr := r.db.WithContext(ctx).Order("title").Find(&list).Errorreturn list, err}func (r *problemSetRepository) Update(ctx context.Context, ps entity.ProblemSet) error {return r.db.WithContext(ctx).Model(&entity.ProblemSet{}).Where("id = ?", ps.Id).Updates(ps).Error}func (r *problemSetRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.ProblemSet{}).Error}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ProblemSetRepository interface {Create(ctx context.Context, ps entity.ProblemSet) errorGet(ctx context.Context, id uuid.UUID) (entity.ProblemSet, error)Update(ctx context.Context, ps entity.ProblemSet) errorDelete(ctx context.Context, id uuid.UUID) errorList(ctx context.Context) ([]entity.ProblemSet, error)}type problemSetRepository struct {db *gorm.DB}func NewProblemSetRepository(db *gorm.DB) ProblemSetRepository {return &problemSetRepository{db: db}}func (r *problemSetRepository) Create(ctx context.Context, ps entity.ProblemSet) error {return r.db.WithContext(ctx).Create(&ps).Error}func (r *problemSetRepository) Get(ctx context.Context, id uuid.UUID) (entity.ProblemSet, error) {var ps entity.ProblemSeterr := r.db.WithContext(ctx).First(&ps, "id = ?", id).Errorreturn ps, err}func (r *problemSetRepository) List(ctx context.Context) ([]entity.ProblemSet, error) {var list []entity.ProblemSeterr := r.db.WithContext(ctx).Order("title").Find(&list).Errorreturn list, err}func (r *problemSetRepository) Update(ctx context.Context, ps entity.ProblemSet) error {return r.db.WithContext(ctx).Model(&entity.ProblemSet{}).Where("id = ?", ps.Id).Updates(ps).Error}func (r *problemSetRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.ProblemSet{}).Error}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type QuestionsRepository interface {Create(ctx context.Context, q entity.Questions) errorGet(ctx context.Context, id uuid.UUID) (entity.Questions, error)Update(ctx context.Context, q entity.Questions) errorDelete(ctx context.Context, id uuid.UUID) errorListByProblemSet(ctx context.Context, problemSetId uuid.UUID) ([]entity.Questions, error)}type questionsRepository struct{ db *gorm.DB }func NewQuestionsRepository(db *gorm.DB) QuestionsRepository {return &questionsRepository{db}}func (r *questionsRepository) Create(ctx context.Context, q entity.Questions) error {return r.db.WithContext(ctx).Create(&q).Error}func (r *questionsRepository) Get(ctx context.Context, id uuid.UUID) (entity.Questions, error) {var q entity.Questionserr := r.db.WithContext(ctx).First(&q, "id = ?", id).Errorreturn q, err}func (r *questionsRepository) Update(ctx context.Context, q entity.Questions) error {return r.db.WithContext(ctx).Model(&entity.Questions{}).Where("id = ?", q.Id).Updates(q).Error}func (r *questionsRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.Questions{}).Error}func (r *questionsRepository) ListByProblemSet(ctx context.Context, problemSetId uuid.UUID) ([]entity.Questions, error) {var q []entity.Questionserr := r.db.WithContext(ctx).Where("problem_set_id = ?", problemSetId).Order("id").Find(&q).Errorreturn q, err}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type QuestionsRepository interface {Create(ctx context.Context, q entity.Questions) errorGet(ctx context.Context, id uuid.UUID) (entity.Questions, error)Update(ctx context.Context, q entity.Questions) errorDelete(ctx context.Context, id uuid.UUID) errorListByProblemSet(ctx context.Context, problemSetId uuid.UUID) ([]entity.Questions, error)}type questionsRepository struct{ db *gorm.DB }func NewQuestionsRepository(db *gorm.DB) QuestionsRepository {return &questionsRepository{db}}func (r *questionsRepository) Create(ctx context.Context, q entity.Questions) error {return r.db.WithContext(ctx).Create(&q).Error}func (r *questionsRepository) Get(ctx context.Context, id uuid.UUID) (entity.Questions, error) {var q entity.Questionserr := r.db.WithContext(ctx).First(&q, "id = ?", id).Errorreturn q, err}func (r *questionsRepository) Update(ctx context.Context, q entity.Questions) error {return r.db.WithContext(ctx).Model(&entity.Questions{}).Where("id = ?", q.Id).Updates(q).Error}func (r *questionsRepository) Delete(ctx context.Context, id uuid.UUID) error {return r.db.WithContext(ctx).Where("id = ?", id).Delete(&entity.Questions{}).Error}func (r *questionsRepository) ListByProblemSet(ctx context.Context, problemSetId uuid.UUID) ([]entity.Questions, error) {var q []entity.Questionserr := r.db.WithContext(ctx).Where("problem_set_id = ?", problemSetId).Order("id").Find(&q).Errorreturn q, err}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ResultRepository interface {Create(ctx context.Context, r *entity.Result) errorGetById(ctx context.Context, id uuid.UUID) (entity.Result, error)Update(ctx context.Context, r *entity.Result) errorListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Result, error)GetByAttemptId(ctx context.Context, attemptId uuid.UUID) (entity.Result, error)}type resultRepository struct{ db *gorm.DB }func NewResultRepository(db *gorm.DB) ResultRepository {return &resultRepository{db}}func (r *resultRepository) Create(ctx context.Context, rs *entity.Result) error {return r.db.WithContext(ctx).Create(rs).Error}func (r *resultRepository) GetByAttemptId(ctx context.Context, attemptId uuid.UUID) (entity.Result, error) {var rs entity.Resulterr := r.db.WithContext(ctx).Preload("ExamEventAttempt").First(&rs, "attempt_id = ?", attemptId).Errorreturn rs, err}func (r *resultRepository) GetById(ctx context.Context, id uuid.UUID) (entity.Result, error) {var rs entity.Resulterr := r.db.WithContext(ctx).Preload("Account").Preload("Event").Preload("ProblemSet").Preload("ExamEventAttempt").First(&rs, "id = ?", id).Errorreturn rs, err}func (r *resultRepository) Update(ctx context.Context, rs *entity.Result) error {return r.db.WithContext(ctx).Model(&entity.Result{}).Where("id = ?", rs.Id).Updates(rs).Error}func (r *resultRepository) ListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Result, error) {var list []entity.Resulterr := r.db.WithContext(ctx).Where("event_id = ?", eventId).Preload("Account").Find(&list).Errorreturn list, err}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960package repositoriesimport ("context"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/google/uuid""gorm.io/gorm")type ResultRepository interface {Create(ctx context.Context, r *entity.Result) errorGetById(ctx context.Context, id uuid.UUID) (entity.Result, error)Update(ctx context.Context, r *entity.Result) errorListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Result, error)GetByAttemptId(ctx context.Context, attemptId uuid.UUID) (entity.Result, error)}type resultRepository struct{ db *gorm.DB }func NewResultRepository(db *gorm.DB) ResultRepository {return &resultRepository{db}}func (r *resultRepository) Create(ctx context.Context, rs *entity.Result) error {return r.db.WithContext(ctx).Create(rs).Error}func (r *resultRepository) GetByAttemptId(ctx context.Context, attemptId uuid.UUID) (entity.Result, error) {var rs entity.Resulterr := r.db.WithContext(ctx).Preload("ExamEventAttempt").First(&rs, "attempt_id = ?", attemptId).Errorreturn rs, err}func (r *resultRepository) GetById(ctx context.Context, id uuid.UUID) (entity.Result, error) {var rs entity.Resulterr := r.db.WithContext(ctx).Preload("Account").Preload("Event").Preload("ProblemSet").Preload("ExamEventAttempt").First(&rs, "id = ?", id).Errorreturn rs, err}func (r *resultRepository) Update(ctx context.Context, rs *entity.Result) error {return r.db.WithContext(ctx).Model(&entity.Result{}).Where("id = ?", rs.Id).Updates(rs).Error}func (r *resultRepository) ListByEvent(ctx context.Context, eventId uuid.UUID) ([]entity.Result, error) {var list []entity.Resulterr := r.db.WithContext(ctx).Where("event_id = ?", eventId).Preload("Account").Find(&list).Errorreturn list, err}
123456789101112131415161718192021222324252627282930313233343536373839package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func AcademyRouter(router *gin.Engine, middleware provider.MiddlewareProvider, controller provider.ControllerProvider) {academyController := controller.ProvideAcademyController()authenticationMiddleware := middleware.ProvideAuthenticationMiddleware()routerGroup := router.Group("/api/v1/academy")routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){// ADMINadminGroup := routerGroup.Group("/admin", authenticationMiddleware.VerifyAccount){// CRUD for AcademiesadminGroup.POST("/", academyController.CreateAcademy)adminGroup.GET("/id/:id/detail", academyController.GetAcademyDetail)adminGroup.PUT("/id/:id", academyController.UpdateAcademy)adminGroup.DELETE("/id/:id", academyController.DeleteAcademy)// Creation of Sub-resourcesadminGroup.POST("/materials", academyController.CreateMaterial)adminGroup.POST("/contents", academyController.CreateContent)}// USERrouterGroup.GET("/", authenticationMiddleware.VerifyAccount, academyController.ListAcademies)routerGroup.GET("/:academy_slug", authenticationMiddleware.VerifyAccount, academyController.GetAcademy)routerGroup.GET("/:academy_slug/:material_slug", authenticationMiddleware.VerifyAccount, academyController.GetMaterial)routerGroup.GET("/:academy_slug/:material_slug/:order", authenticationMiddleware.VerifyAccount, academyController.GetContent)routerGroup.POST("/:academy_slug/:material_slug/:order", authenticationMiddleware.VerifyAccount, academyController.UpdateContentProgress)}}123456789101112131415161718192021222324252627282930313233343536373839404142434445package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func AcademyRouter(router *gin.Engine, middleware provider.MiddlewareProvider, controller provider.ControllerProvider) {academyController := controller.ProvideAcademyController()authenticationMiddleware := middleware.ProvideAuthenticationMiddleware()routerGroup := router.Group("/api/v1/academy")routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){// ================= ADMIN SECTION =================adminGroup := routerGroup.Group("/admin", authenticationMiddleware.VerifyAccount){// CRUD for AcademiesadminGroup.POST("/", academyController.CreateAcademy)adminGroup.GET("/id/:id/detail", academyController.GetAcademyDetail)adminGroup.PUT("/id/:id", academyController.UpdateAcademy)adminGroup.DELETE("/id/:id", academyController.DeleteAcademy)// MaterialsadminGroup.POST("/materials", academyController.CreateMaterial)adminGroup.DELETE("/materials/:id", academyController.DeleteMaterial)// ContentsadminGroup.POST("/contents", academyController.CreateContent)adminGroup.DELETE("/contents/:id", academyController.DeleteContent)}// ================= USER SECTION =================// Public/Student endpoints (Authenticated)routerGroup.GET("/", authenticationMiddleware.VerifyAccount, academyController.ListAcademies)routerGroup.GET("/:academy_slug", authenticationMiddleware.VerifyAccount, academyController.GetAcademy)routerGroup.GET("/:academy_slug/:material_slug", authenticationMiddleware.VerifyAccount, academyController.GetMaterial)routerGroup.GET("/:academy_slug/:material_slug/:order", authenticationMiddleware.VerifyAccount, academyController.GetContent)// Update ProgressrouterGroup.POST("/:academy_slug/:material_slug/:order", authenticationMiddleware.VerifyAccount, academyController.UpdateContentProgress)}}
123456789101112131415161718package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func AccountDetailRouter(router *gin.Engine, middleware provider.MiddlewareProvider, controller provider.ControllerProvider) {routerGroup := router.Group("/api/v1/account")accountDetailController := controller.ProvideAccountDetailController()authenticationMiddleware := middleware.ProvideAuthenticationMiddleware()routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){routerGroup.GET("/me", authenticationMiddleware.VerifyAccount, accountDetailController.GetDetail)routerGroup.PUT("/me", authenticationMiddleware.VerifyAccount, accountDetailController.UpdateDetail)}}123456789101112131415161718package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func AccountDetailRouter(router *gin.Engine, middleware provider.MiddlewareProvider, controller provider.ControllerProvider) {routerGroup := router.Group("/api/v1/account")accountDetailController := controller.ProvideAccountDetailController()authenticationMiddleware := middleware.ProvideAuthenticationMiddleware()routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){routerGroup.GET("/me", authenticationMiddleware.VerifyAccount, accountDetailController.GetDetail)routerGroup.PUT("/me", authenticationMiddleware.VerifyAccount, accountDetailController.UpdateDetail)}}
1234567891011121314151617package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func EmailVerificationRouter(router *gin.Engine, controller provider.ControllerProvider) {emailVerificationController := controller.ProvideEmailVerificationController()routerGroup := router.Group("/api/v1/email")routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){routerGroup.POST("/verify", emailVerificationController.Validate)routerGroup.POST("/create-verification", emailVerificationController.Create)}}1234567891011121314151617package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func EmailVerificationRouter(router *gin.Engine, controller provider.ControllerProvider) {emailVerificationController := controller.ProvideEmailVerificationController()routerGroup := router.Group("/api/v1/email")routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){routerGroup.POST("/verify", emailVerificationController.Validate)routerGroup.POST("/create-verification", emailVerificationController.Create)}}
12345678910111213141516171819package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func EventRouter(router *gin.Engine, middleware provider.MiddlewareProvider, controller provider.ControllerProvider) {eventController := controller.ProvideEventController()authenticationMiddleware := middleware.ProvideAuthenticationMiddleware()routerGroup := router.Group("api/v1/events")routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){routerGroup.GET("/", authenticationMiddleware.VerifyAccount, eventController.List)routerGroup.GET("/:event_slug", authenticationMiddleware.VerifyAccount, eventController.DetailBySlug)routerGroup.POST("/register-event", authenticationMiddleware.VerifyAccount, eventController.Join)}}12345678910111213141516171819package routerimport ("abdanhafidz.com/go-boilerplate/provider""github.com/gin-contrib/gzip""github.com/gin-gonic/gin")func EventRouter(router *gin.Engine, middleware provider.MiddlewareProvider, controller provider.ControllerProvider) {eventController := controller.ProvideEventController()authenticationMiddleware := middleware.ProvideAuthenticationMiddleware()routerGroup := router.Group("api/v1/events")routerGroup.Use(gzip.Gzip(gzip.DefaultCompression)){routerGroup.GET("/", authenticationMiddleware.VerifyAccount, eventController.List)routerGroup.GET("/:event_slug", authenticationMiddleware.VerifyAccount, eventController.DetailBySlug)routerGroup.POST("/register-event", authenticationMiddleware.VerifyAccount, eventController.Join)}}
.env.exampleAdded+13
README.md+8-8
api_spec.txt+117-117
config/database_config.go+32-27
config/env_config.go+16-1
config/jwt_config.go+24-24
config/supabase.goAdded+15
controllers/academy_controller.go+228-145
controllers/upload_controller.goAdded+222
do_inject_config.ps1+434-434
do_inject_controllers.ps1+309-309
do_inject_middleware.ps1+311-311
do_inject_repository.ps1+326-326
do_inject_services.ps1+382-382
go.mod+1
go.sum+2
middleware/authentication_middleware.go+48-48
middleware/authorization_middleware.go+43-43
middleware/middleware.go+1-1
models/dto/academy_dto.go+30-30
models/dto/account_details_dto.go+19-19
models/dto/event_dto.go+20-20
models/dto/exam_dto.go+23-23
models/dto/option_dto.go+12-12
models/dto/upload_dto.goAdded+43
models/entity/contant.goAdded+7
models/entity/entity.go+15
models/error/error.go+39-15
provider/config_provider.go+59-38
provider/controller_provider.go+106-90
provider/middleware_provider.go+30-30
provider/provider.go+85-70
provider/repositories_provider.go+178-170
provider/services_provider.go+121-103
provider/storage_interface.goAdded+13
provider/supabase_storage.goAdded+42
repositories/academy_repository.go+232-157
repositories/exam_event_answer_repository.go+59-59
repositories/exam_event_assign_repository.go+47-47
repositories/exam_event_attempt_repository.go+55-55
repositories/exam_event_repository.go+85-85
repositories/file_repository.goAdded+43
repositories/problem_set_exam_assign_repository.go+40-40
repositories/problem_set_repository.go+57-57
repositories/question_repository.go+55-55
repositories/result_repository.go+60-60
router/academy_router.go+44-38
router/account_detail_router.go+18-18
router/email_router.go+17-17
router/event_router.go+19-19