axyut commited on
Commit ·
8a73406
1
Parent(s): 4a3d5c5
root route setup for api
Browse filesFiles changed (6)
- .air.toml+1-1
- .gitattributesDeleted-2
- docker-compose.yml+4-4
- go.mod+8-1
- go.sum+15
- main.go+170-21
14 unmodified lines1516171819202114 unmodified linesfull_bin = ""include_dir = []include_ext = ["go", "tpl", "tmpl", "html"]include_file = []kill_delay = "0s"log = "build-errors.log"poll = false14 unmodified lines1516171819202114 unmodified linesfull_bin = ""include_dir = []include_ext = ["go", "tpl", "tmpl", "html"]include_file = [".env"]kill_delay = "0s"log = "build-errors.log"poll = false
12tmp/niyam filter=lfs diff=lfs merge=lfs -texttmp/main filter=lfs diff=lfs merge=lfs -text7 unmodified lines89101112131415161718197 unmodified linesdockerfile: Dockerfile.dev # Refers to your main Dockerfiletarget: builder # IMPORTANT: Build only the 'builder' stage for devports:- "7860:7860" # Map host port 8080 to container port 8080volumes:- .:/app # Mount your current host directory into /app inside the containerenvironment:# Any environment variables your app needs for dev- PORT=7860command: air # Run the 'air' command, which watches files and rebuilds# Optional: If you need to specify the main Go file path for air,# you might need an .air.toml config file, or adjust the command.7 unmodified lines89101112131415161718197 unmodified linesdockerfile: Dockerfile.dev # Refers to your main Dockerfiletarget: builder # IMPORTANT: Build only the 'builder' stage for devports:- "${PORT}:${PORT}"volumes:- .:/app # Mount your current host directory into /app inside the container# environment:# Any environment variables your app needs for dev# - PORT=7860command: air # Run the 'air' command, which watches files and rebuilds# Optional: If you need to specify the main Go file path for air,# you might need an .air.toml config file, or adjust the command.
12345678910111213module github.com/axyut/lawopsgo 1.24.2require (github.com/danielgtaylor/huma/v2 v2.32.0github.com/go-chi/chi/v5 v5.1.0)require (github.com/fxamacker/cbor/v2 v2.7.0 // indirectgithub.com/x448/float16 v0.8.4 // indirect)1234567891011121314151617181920module github.com/axyut/niyamAPIgo 1.24.2require (github.com/danielgtaylor/huma/v2 v2.32.0github.com/go-chi/chi/v5 v5.1.0github.com/joho/godotenv v1.5.1github.com/shirou/gopsutil v3.21.11+incompatible)require (github.com/fxamacker/cbor/v2 v2.7.0 // indirectgithub.com/go-ole/go-ole v1.2.6 // indirectgithub.com/tklauser/go-sysconf v0.3.15 // indirectgithub.com/tklauser/numcpus v0.10.0 // indirectgithub.com/x448/float16 v0.8.4 // indirectgithub.com/yusufpapurcu/wmi v1.2.4 // indirectgolang.org/x/sys v0.31.0 // indirect)
5 unmodified lines67891011121314151617185 unmodified linesgithub.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=5 unmodified lines67891011121314151617181920212223242526272829303132335 unmodified linesgithub.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4=github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4=github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso=github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ=github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647482 unmodified linesimport ("context""fmt""net/http""github.com/danielgtaylor/huma/v2""github.com/danielgtaylor/huma/v2/adapters/humachi""github.com/go-chi/chi/v5"_ "github.com/danielgtaylor/huma/v2/formats/cbor")// GreetingOutput represents the greeting operation response.type GreetingOutput struct {Body struct {Message string `json:"message" example:"Hello, world!" doc:"Greeting message"`}}func main() {// Create a new router & API.router := chi.NewMux()api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))// Register GET /greeting/{name} handler.huma.Get(api, "/greeting/{name}", func(ctx context.Context, input *struct {Name string `path:"name" maxLength:"30" example:"world" doc:"Name to greet"`}) (*GreetingOutput, error) {resp := &GreetingOutput{}resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)return resp, nil})port := "7860" // Default port// You might read the port from an environment variable for flexibility// if p := os.Getenv("PORT"); p != "" {// port = p// }addr := fmt.Sprintf(":%s", port) // Listen on all interfacesfmt.Printf("Server starting on http://localhost%s/docs\n", addr)err := http.ListenAndServe(addr, router) // <--- THIS IS KEYif err != nil {fmt.Printf("Server failed to start: %v\n", err)}}2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961972 unmodified linesimport ("context""fmt""log""net""net/http""os""os/signal""syscall""time""github.com/danielgtaylor/huma/v2""github.com/danielgtaylor/huma/v2/adapters/humachi""github.com/go-chi/chi/v5""github.com/go-chi/chi/v5/middleware""github.com/joho/godotenv""github.com/shirou/gopsutil/cpu"_ "github.com/danielgtaylor/huma/v2/formats/cbor")var startTime = time.Now()type MetadataOutput struct {Body struct {Service string `json:"service" example:"My API"`Version string `json:"version" example:"v1"`Description string `json:"description" example:"API description"`Status string `json:"status" example:"operational"`Uptime string `json:"uptime" example:"8d 19h 16m"`Health HealthStatus `json:"health"`Documentation string `json:"documentation" example:"/docs"`Links MetadataLinks `json:"links"`Contact MetadataContact `json:"contact"`Environment string `json:"environment" example:"development"`}}type HealthStatus struct {Database string `json:"database" example:"ok"`Server string `json:"server" example:"ok"`Load float64 `json:"load" example:"11.35"`}type MetadataLinks struct {Self string `json:"self" example:"/"`PrivacyPolicy string `json:"privacyPolicy" example:"/api/terms_condition"`}type MetadataContact struct {Name string `json:"name" example:"API Support"`Email string `json:"email" example:"mail@achyutkoirala.com.np"`URL string `json:"url" example:"/contact"`}type HealthCheckOutput struct {Body struct {Status string `json:"status" example:"healthy" doc:"API health status"`}}func main() {err := godotenv.Load()if err != nil {log.Printf("No .env file found or error loading .env: %v. Proceeding without it.", err)} else {log.Println(".env file loaded successfully.")}port := os.Getenv("PORT")if port == "" {port = "8080" // Default port if not specified in .env or actual environment}listenAddr := ":" + portrouter := chi.NewMux()// chi middleware for request logging and panic recoveryrouter.Use(middleware.Logger)router.Use(middleware.Recoverer) // recover from panics, prevents server crash// Store the Huma config in a variable to access its fieldsapiConfig := huma.DefaultConfig("Niyam API", "1.0.0")apiConfig.Info.Description = "API/Backend service for the Niyam application."api := humachi.New(router, apiConfig) // Pass the config variable here// Root endpoint "/"huma.Get(api, "/", func(ctx context.Context, input *struct{}) (*MetadataOutput, error) {// Log.Println for specific handler entry/exit is now less critical with middleware.Logger// log.Println("Received root metadata request.")// Calculate uptimeuptimeDuration := time.Since(startTime)uptime := fmt.Sprintf("%dd %dh %dm",int(uptimeDuration.Hours()/24),int(uptimeDuration.Hours())%24,int(uptimeDuration.Minutes())%60,)// Get actual CPU load percentagecpuPercentages, err := cpu.Percent(time.Second, false)var currentLoad float64if err != nil {log.Printf("Error getting CPU load: %v", err)currentLoad = -1.0 // Indicate error or unknown load} else if len(cpuPercentages) > 0 {currentLoad = cpuPercentages[0] // Get the overall CPU percentage} else {currentLoad = 0.0 // No CPU data or 0%}resp := &MetadataOutput{}resp.Body.Service = apiConfig.Info.Titleresp.Body.Version = apiConfig.Info.Versionresp.Body.Description = apiConfig.Info.Descriptionresp.Body.Status = "operational"resp.Body.Uptime = uptimeresp.Body.Health = HealthStatus{Database: "ok", // TODO: check DB connectionServer: "ok",Load: currentLoad,}resp.Body.Documentation = "/docs"resp.Body.Links = MetadataLinks{Self: "/",PrivacyPolicy: "/api/terms_and_condition",}resp.Body.Contact = MetadataContact{Name: "API Support",Email: "mail@achyutkoirala.com.np",URL: "/contact",}// Get environment from an ENV var, default to "development"appEnv := os.Getenv("APP_ENV")if appEnv == "" {appEnv = "development"}resp.Body.Environment = appEnvreturn resp, nil})// Health Check Endpointhuma.Get(api, "/healthz", func(ctx context.Context, input *struct{}) (*HealthCheckOutput, error) {// log.Println("Health check requested.") // Logger middleware will cover this.resp := &HealthCheckOutput{}resp.Body.Status = "healthy"return resp, nil})// Dynamically Get the Actual Host and Port (for logging)listener, err := net.Listen("tcp", listenAddr)if err != nil {log.Fatalf("Server failed to listen on %s: %v", listenAddr, err)}defer listener.Close()actualAddr := listener.Addr().String()log.Printf("Server listening on %s (Access docs at http://localhost%s/docs)\n", actualAddr, listener.Addr().String())// Graceful Shutdownquit := make(chan os.Signal, 1)signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)srv := &http.Server{Addr: listener.Addr().String(),Handler: router,ReadTimeout: 5 * time.Second,WriteTimeout: 10 * time.Second,IdleTimeout: 120 * time.Second,}go func() {log.Printf("Starting HTTP server on %s...", srv.Addr)if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {log.Fatalf("HTTP server failed: %v", err)}log.Println("HTTP server stopped.")}()sig := <-quitlog.Printf("Received signal '%s'. Shutting down server...", sig)ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()if err := srv.Shutdown(ctx); err != nil {log.Fatalf("Server shutdown failed: %v", err)}log.Println("Server gracefully shut down.")}
.air.toml+1-1
.gitattributesDeleted-2
docker-compose.yml+4-4
go.mod+8-1
go.sum+15
main.go+170-21