Initial commit

This commit is contained in:
Arkaprabha Chakraborty
2025-12-01 08:29:49 +05:30
commit 39c61b7790
20 changed files with 4206 additions and 0 deletions

48
internal/server/routes.go Normal file
View File

@@ -0,0 +1,48 @@
package server
import (
"net/http"
"billit/cmd/web"
"github.com/a-h/templ"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
func (s *Server) RegisterRoutes() http.Handler {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"https://*", "http://*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
AllowHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true,
MaxAge: 300,
}))
fileServer := http.FileServer(http.FS(web.Files))
e.GET("/assets/*", echo.WrapHandler(fileServer))
e.GET("/web", echo.WrapHandler(templ.Handler(web.HelloForm())))
e.POST("/hello", echo.WrapHandler(http.HandlerFunc(web.HelloWebHandler)))
e.GET("/", s.HelloWorldHandler)
e.GET("/health", s.healthHandler)
return e
}
func (s *Server) HelloWorldHandler(c echo.Context) error {
resp := map[string]string{
"message": "Hello World",
}
return c.JSON(http.StatusOK, resp)
}
func (s *Server) healthHandler(c echo.Context) error {
return c.JSON(http.StatusOK, s.db.Health())
}

View File

@@ -0,0 +1,39 @@
package server
import (
"encoding/json"
"github.com/labstack/echo/v4"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
resp := httptest.NewRecorder()
c := e.NewContext(req, resp)
s := &Server{}
// Assertions
if err := s.HelloWorldHandler(c); err != nil {
t.Errorf("handler() error = %v", err)
return
}
if resp.Code != http.StatusOK {
t.Errorf("handler() wrong status code = %v", resp.Code)
return
}
expected := map[string]string{"message": "Hello World"}
var actual map[string]string
// Decode the response body into the actual map
if err := json.NewDecoder(resp.Body).Decode(&actual); err != nil {
t.Errorf("handler() error decoding response body: %v", err)
return
}
// Compare the decoded response with the expected value
if !reflect.DeepEqual(expected, actual) {
t.Errorf("handler() wrong response body. expected = %v, actual = %v", expected, actual)
return
}
}

39
internal/server/server.go Normal file
View File

@@ -0,0 +1,39 @@
package server
import (
"fmt"
"net/http"
"os"
"strconv"
"time"
_ "github.com/joho/godotenv/autoload"
"billit/internal/database"
)
type Server struct {
port int
db database.Service
}
func NewServer() *http.Server {
port, _ := strconv.Atoi(os.Getenv("PORT"))
NewServer := &Server{
port: port,
db: database.New(),
}
// Declare Server config
server := &http.Server{
Addr: fmt.Sprintf(":%d", NewServer.port),
Handler: NewServer.RegisterRoutes(),
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
return server
}