albertwidi/go-project-example - GitHub

文章推薦指數: 80 %
投票人數:10人

Go Project Example. Contribute to albertwidi/go-project-example development by creating an account on GitHub. Skiptocontent {{message}} albertwidi / go-project-example Public Notifications Star 40 Fork 28 GoProjectExample GPL-3.0License 40 stars 28 forks Star Notifications Code Issues 0 Pullrequests 0 Actions Projects 0 Wiki Security Insights More Code Issues Pullrequests Actions Projects Wiki Security Insights master Branches Tags Couldnotloadbranches Nothingtoshow Loading {{refName}} default Couldnotloadtags Nothingtoshow {{refName}} default Loading 2 branches 0 tags Code Loading Latestcommit   Gitstats 66 commits Files Permalink Failedtoloadlatestcommitinformation. Type Name Latestcommitmessage Committime .github/workflows     cmd/project     database     debug     docs     internal     scripts     .gitignore     LICENSE     Makefile     README.md     docker-compose.yml     go.mod     go.sum     project.config.toml     project.env.toml     Viewcode GoProjectExample DesigningProjectForIndustrialProgramming TheProject Use-cases ProjectStack GettingStarted Requirements CreateDatabaseAndMigrate Flags Configuration EnvironmentState ProjectStructure Cmd Internal CodeStructure Components Server Usecase Repository Entity Layers MicroserviceStructureInsideMonolith ErrorHandling Misc SetDefaultTimezone References GoErrors README.md GoProjectExample ThisisanexampleforGoproject. Themotivationbehindthisprojectistolearnandbroadenmylimitedknowledgeaboutprogramming,projectdesign,concepts,algorithm,andespecially,Goitself.Inthisproject,Iwilltrytoimplementbusinesslogic/flowintoGoprogramforvarioususe-cases. DesigningProjectForIndustrialProgramming Whatisindustrialprogramming?PeterBourgonexplaintheterms,as: Inastartuporcorporateenvironment. Withinateamwhereengineerscomeandgo. Oncodethatoutlivesanysingleengineer. Servinghighlymutablebusinessrequirements. TheProject TheprojectthemeisProperty.IwilltrytobuildaPropertyapplication,wherepeopleabletosearchandbooktheproperty. Use-cases Userswereabletoregisterandlogin. UserswereabletoregistertheirProperties. Registerthepropertydetail Uploadthepropertyimage UserswereabletobookaProperty. Userswereabletoreceivenotificationsandhaveanotificationinbox. ProjectStack Thisprojectisusing: PostgreSQLforthemaindatabase Redisfork/v,usersessionmanagement,caching. GettingStarted Thisisguidetogetstartedwiththisprojectandinstallingdependenciesrequiredforrunningthisprojectlocally Requirements Make Docker SodaCLIfromgobuffalo.Youcaninstallthisbyusingmakeinstall-deps CreateDatabaseAndMigrate Tocreateandmigratethedatabase,wewillusesodaCLIcreatedbygobuffalo.Thecommandiswrapperbythisscript. Usethiscommandtofullycreateandmigratethedatabseschema: makedbup Flags Thefollowingflagsisavaiabletohelptheprojectconfigurationanddebugparameters. --config_filedefinewheretheconfigurationfileislocated --env_filedefinewhereenvironmentvariablefileislocated,thisisahelperfiletosetenvironmentvariable. --debugdefinethedebugconfigurationfortheproject.Withflagkey: -debug=server=1toturnonthedebugserver. -debug=testconfig=1totesttheconfigurationoftheproject. example:--debug=-debugserver=1-testconfig=1 Configuration Forapplicatoinconfiguration,config-fileisusedandlocatedontherootprojectdirectory.Theconfiguration-fileiswrittenintomlgrammar. Theconfigurationvalueintheconfiguration-fileisembedasenvironment-variablevalue.Thevaluewillbereplacedbytheenvironment-variablevalueinruntimeorwhenprogramstarted.Tohelptheprocess,theprojectusethehelpofenvironment-variablefile.Theenvironment-variablefilesischoosenbecauseitissimpleraswecanhavemultiplefilesandwecanhide/ignorethefileforspecificuse-case,forexample,secretvalueofclient_idandclient_secretofsomecloudvendor. Themixedofconfiguration-variableandenvironment-variableisusedtohelppeopleinprojecttoseewhatconfigurationstructureisexistswithintheproject,andabletodynamicallychangeddependsontheenvironmentvariablesvalue. ConfigurationStructure: Servers[object]: Main[object]: Address:addressofthemainserver,forexamplelocalhost:8000 Admin[object]: Address:adressoftheadminserver,forexamplelocalhost:5726 Debug[object]: Address[string]:addressofdebugserver,forexamplelocalhost:9000 Log level:levelofthelog,debug|info|warn|error|fatal file:filelocationtostorethelog color:printwithcolorontheterminal Resources ObjectStorage[array] [ObjectStorageObject] name[string]:nameoftheobjectstorage,forexampleimage Database[object] Connect[array] [ConnectObject] name:nameofthedatabase,forexampleuser driver:thedriverofdatabase,mysql|postgres leaderobject dsn:thedsnofdatabaseleader,forexample replicaobject dsn:thedsnofdatabasereplica,forexample Redis[object]: Connect[array]: [ConnectObject] Name[string]:nameofredis,forexamplesession Address[string]:addressofredisserver,forexamplelocalhost:6379 Resourcesconfigurationallowstheprojecttoeasilyaddandremoveresources.Because,astheprojectgrow,wemightneedtoaddmoreconnectiontomorepostgres,redisorothertypeofdatabase.Insteadofhandlingtheconnectionmanuallyinsidethecode,awrappeerisaddedtoholdalltheconnectiontoresources EnvironmentState Theprojecthavenoenvironmentstate.Differentflagsandconfigurationvalueisusedindifferentenvironment. Environmentstatelikedev,staging,andproductionisusuallyusedtocheckinwhatenvironmenttheprogram/applicationisrunning.Fromexperience,thisconsideredharmfulfortheprogramitself,asdevelopertemptedtoabusethestateformanythings.Developertemptedtoabusethestatebecausethefunctionisavailable,andsometimesitistheeasiestwaytoaccomplishsomegoals.Byusingthestate,peopleintheprojectarecuttingedgesandcreateconditionalexpressionforvarioususe-cases.Thisleadstobrokenmentalmodel,bugs,andedge-casestotheproductwhichmakelifeharderforthemaintainers. Forexample,incode: ifenv.IsDevelopment(){ //dosomethingonlyindev } ifenv.IsStaging(){ //dosomethingonlyinstaging } ifenv.IsProduction(){ //dosomethingonlyinproduction } Thisenvironmentstate,sometimesalsousedforconfigurationdirective.Whentheconfigurationdirectiveisgatedbytheenvironmentstate,anotherproblemoccur.Because,configurationforeachenvironmentmighthavedifferentvariablesandvalue,anddifferentconfigurationfilecanmeandifferentthings. Forexample,inconfigurationwithspecproject.{environment_name}.config.toml: project.dev.config.toml project.staging.config.toml project.production.config.toml Or,imagineifyouhavemanydifferentconfigurations(withvariousreasons/decision)usingthiskindofdirective: project.dev.config1.toml project.staging.config1.toml project.production.config1.toml project.dev.config2.toml project.staging.config2.toml project.production.config2.toml Multipleconfigurationswithenvironmentstatedirective,usuallyusedtoaddressdifferentconfigurationsineachenvironments.Forexample,whenadatabaseispointingtooneinstanceindevbutnotinstaging,whichcompletelydifferent.Or,whendoingsomemigrationwewanttogetridofsomeconfigurationvariablesinsomeenvironment.Thisallarevaliduse-cases,andthegivensolutionbyusingtheenvironmentstateforconfigurationdirectiveworks.Usually,untiltheconfigurationisbecometoolonganddifferentforeachenvironments,thenturningintoproblemsforthemaintainers. Assometimesweneedtorunwithsomespecialconfigurationinnon-productionorinproductionenvironment,thismightbeabletoachievedbyusingthecombinationofflagsandconfiguration-file.VariablesfromflagsandconfigurationismoreclearandstraightforwardthanIsEnvrionment,andcanbeusedtocheckedthedesignchoices,dowehavetoomanyhacks?Why?Forwhateverreason,theflags/configurationvariablesbetweenenvironmentsshouldstaythesame,tomaintainconsistency. But,intheend,itdepends/backtoeachprojectpoliciesandgovernance. ProjectStructure Cmd AllGomainprogramsislocatedingo-project-example/cmd/*folder. Internal Tobeadded CodeStructure Asstatedatthetopofthisdocument,thedesigncontainsseverallayersandcomponentsandverymuchsimilartoonionringorcleanarchitectureattempt. But,let'stalkaboutthecomponentsfirst. Components Server Usecase Repository Entity Server Iswhereallthehttphandlerexists.Thislayerisresponsibletoholdallthehttphandlersandrequestvalidation. MainServer Mainserverforservingmainapplication.Allbusinessuse-casehandlerexistswithinthisserver. AdminServer Adminserverisaserverforadministrationalpurpose.Onbydefaultandshouldnotopentopublic. Use-caseforadminserver: /metricsendpoint /resource/statusendpoint pprofendpoint checkcurrentconfigurationvalue DebugServer Debugserverisaserverforexperimentalpurpose,andshouldbeenabledwithaspesificflag.Thisservershouldnotbetriggeredinproductionenvironment. Use-casefordebugserver: Loginbypass Servefileserverforlocalobjectstorage Usecase Tobeadded Repository Tobeadded Entity Tobeadded Layers Tobeadded MicroserviceStructureInsideMonolith Whenacompanybecomelargerandthenumberofpeopleandteamsincreaserapidly,itismakesensetoadoptmicroservicearchitectureforthecompany...tobeadded NOTE Microserviceitselfisnotasilverbullettobeginwith,itsolvesorganizationalscaleproblem,teamsbecomemoreindependentandresponsibleoftheirownproducts,etc.But,italsointroducesalotofproblem,forexamplenetwork,state,andotherdistributedsystemproblems.Beforetakingthispath,itsbesttounderstandwhatproblemsthatwewanttosolvewithmicroservicegainmoreknowledgearoundmicroservice,andhowwewanttotackletheproblemsinsidetheorganization. ErrorHandling InGo,errorsarevalue.ThisisoneoftheoftheGo'sproverbs.So,insteadofthrowingerror,Goprogramwilltreattheerrorasvalueandtheerrorshouldbecheckedorreturnedtothecaller. Don'tjustcheckerrors,handlethemgracefully-Go'sproverbs Checktheerrororreturn,butnotboth.-DaveChanney WhilehandlingerrorinGoisveryeasyandstraightforward,theerroritselfissometimeslackingofcontext. Tobecontinued. Misc SetDefaultTimezone Tosetdefaulttimezoneingoprograms,wecansetanenvironmentvariablenamedTZwhenrunningorinourprogramsbeforetimepackagegetcalled.ThevalueofTZisthelocationofTimezone.Inmycase,itisAsia/Jakarta. Forexample,incode: os.SetEnv("TZ","Asia/Jakarta") or,duringexecution: TZ=Asia/Jakarta./yourbin Whataboutmorethanonetimezoneinasingleapplication? Youcanalwaysusetimepackagefunctioncalledtime.LoadLocationtocreatespesifictimezone/locationtimeobject. Forexample: loc,err:=time.LoadLocation("Asia/Jakarta") iferr!=nil{ //handletheerror } //thisfunctionproducetime.NowspecifiedtolocorAsia/Jakarta nowInLoc:=time.Now().In(loc) References GoErrors Articles https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully https://blog.golang.org/go1.13-errors Videos GopherCon2019:MarwanSulaiman-HandlingGoErrors Code Upspinerrorspackage About GoProjectExample Topics go design example Resources Readme License GPL-3.0License Releases Noreleasespublished Packages0 Nopackagespublished Contributors2     Languages Go 97.9% Other 2.1% Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?