Initial commit
This commit is contained in:
38
internal/server/routes.go
Normal file
38
internal/server/routes.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
)
|
||||
|
||||
func (s *Server) RegisterRoutes() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.Logger)
|
||||
|
||||
r.Get("/", s.HelloWorldHandler)
|
||||
|
||||
r.Get("/health", s.healthHandler)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (s *Server) HelloWorldHandler(w http.ResponseWriter, r *http.Request) {
|
||||
resp := make(map[string]string)
|
||||
resp["message"] = "Hello World"
|
||||
|
||||
jsonResp, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
log.Fatalf("error handling JSON marshal. Err: %v", err)
|
||||
}
|
||||
|
||||
_, _ = w.Write(jsonResp)
|
||||
}
|
||||
|
||||
func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
jsonResp, _ := json.Marshal(s.db.Health())
|
||||
_, _ = w.Write(jsonResp)
|
||||
}
|
||||
39
internal/server/server.go
Normal file
39
internal/server/server.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
|
||||
"gothtest/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
|
||||
}
|
||||
Reference in New Issue
Block a user