feat: Create collection file for routes
This commit is contained in:
39
server/api.go
Normal file
39
server/api.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/tenante/api/database"
|
||||
)
|
||||
|
||||
type ApiServer struct {
|
||||
Port int
|
||||
DatabaseConnection *database.Connection
|
||||
}
|
||||
|
||||
func NewApiServer(port int, database *database.Connection) *ApiServer {
|
||||
return &ApiServer{Port: port, DatabaseConnection: database}
|
||||
}
|
||||
|
||||
func (api *ApiServer) Start() error {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/_/health", api.HealthCheckRoute)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", api.Port),
|
||||
Handler: mux,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
fmt.Printf("🚀 Server starting on %s...\n", srv.Addr)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
13
server/response.go
Normal file
13
server/response.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package server
|
||||
|
||||
type HealthCheckResponse struct {
|
||||
Database bool `json:"database"`
|
||||
API bool `json:"api"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type InternalServerErrorResponse struct {
|
||||
Status string `json:"status"`
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
24
server/route.go
Normal file
24
server/route.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (api *ApiServer) HealthCheckRoute(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
response := HealthCheckResponse{
|
||||
Database: api.DatabaseConnection.Ping(),
|
||||
API: true,
|
||||
Status: "OK",
|
||||
}
|
||||
err := json.NewEncoder(w).Encode(response)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, err := w.Write([]byte("Internal Server Error"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user