first commit
This commit is contained in:
71
internal/server/routes.go
Normal file
71
internal/server/routes.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
func (s *Server) RegisterRoutes() http.Handler {
|
||||
r := gin.Default()
|
||||
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"http://localhost:5173"}, // Add your frontend URL
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
|
||||
AllowHeaders: []string{"Accept", "Authorization", "Content-Type"},
|
||||
AllowCredentials: true, // Enable cookies/auth
|
||||
}))
|
||||
|
||||
r.GET("/", s.HelloWorldHandler)
|
||||
|
||||
r.GET("/health", s.healthHandler)
|
||||
|
||||
r.GET("/websocket", s.websocketHandler)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (s *Server) HelloWorldHandler(c *gin.Context) {
|
||||
resp := make(map[string]string)
|
||||
resp["message"] = "Hello World"
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (s *Server) healthHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, s.db.Health())
|
||||
}
|
||||
|
||||
func (s *Server) websocketHandler(c *gin.Context) {
|
||||
w := c.Writer
|
||||
r := c.Request
|
||||
socket, err := websocket.Accept(w, r, nil)
|
||||
|
||||
if err != nil {
|
||||
log.Printf("could not open websocket: %v", err)
|
||||
_, _ = w.Write([]byte("could not open websocket"))
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
defer socket.Close(websocket.StatusGoingAway, "server closing websocket")
|
||||
|
||||
ctx := r.Context()
|
||||
socketCtx := socket.CloseRead(ctx)
|
||||
|
||||
for {
|
||||
payload := fmt.Sprintf("server timestamp: %d", time.Now().UnixNano())
|
||||
err := socket.Write(socketCtx, websocket.MessageText, []byte(payload))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second * 2)
|
||||
}
|
||||
}
|
||||
32
internal/server/routes_test.go
Normal file
32
internal/server/routes_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHelloWorldHandler(t *testing.T) {
|
||||
s := &Server{}
|
||||
r := gin.New()
|
||||
r.GET("/", s.HelloWorldHandler)
|
||||
// Create a test HTTP request
|
||||
req, err := http.NewRequest("GET", "/", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Create a ResponseRecorder to record the response
|
||||
rr := httptest.NewRecorder()
|
||||
// Serve the HTTP request
|
||||
r.ServeHTTP(rr, req)
|
||||
// Check the status code
|
||||
if status := rr.Code; status != http.StatusOK {
|
||||
t.Errorf("Handler returned wrong status code: got %v want %v", status, http.StatusOK)
|
||||
}
|
||||
// Check the response body
|
||||
expected := "{\"message\":\"Hello World\"}"
|
||||
if rr.Body.String() != expected {
|
||||
t.Errorf("Handler returned unexpected body: got %v want %v", rr.Body.String(), expected)
|
||||
}
|
||||
}
|
||||
47
internal/server/server.go
Normal file
47
internal/server/server.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
|
||||
"api-service/internal/config"
|
||||
"api-service/internal/database"
|
||||
v1 "api-service/internal/routes/v1"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
port int
|
||||
db database.Service
|
||||
}
|
||||
|
||||
func NewServer() *http.Server {
|
||||
// Load configuration
|
||||
cfg := config.LoadConfig()
|
||||
cfg.Validate()
|
||||
|
||||
port, _ := strconv.Atoi(os.Getenv("PORT"))
|
||||
if port == 0 {
|
||||
port = cfg.Server.Port
|
||||
}
|
||||
|
||||
NewServer := &Server{
|
||||
port: port,
|
||||
db: database.New(),
|
||||
}
|
||||
|
||||
// Declare Server config
|
||||
server := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", NewServer.port),
|
||||
Handler: v1.RegisterRoutes(),
|
||||
IdleTimeout: time.Minute,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
return server
|
||||
}
|
||||
Reference in New Issue
Block a user