move auth to auth

This commit is contained in:
2024-12-22 21:33:46 +01:00
parent 877557febe
commit 3c601caf02
21 changed files with 279 additions and 265 deletions

11
pkg/fileExists.go Normal file
View File

@@ -0,0 +1,11 @@
package pkg
import (
"os"
)
// Checks if file on path exists or not
func FileExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}

27
pkg/fileExists_test.go Normal file
View File

@@ -0,0 +1,27 @@
package pkg
import (
"os"
"testing"
)
func TestFileExists(t *testing.T) {
// Create a temporary file for testing
file, err := os.CreateTemp("", "testfile")
if err != nil {
t.Fatalf("Failed to create temporary file: %v", err)
}
defer os.Remove(file.Name())
// Test with an existing file
exists := FileExists(file.Name())
if !exists {
t.Errorf("FileExists(%q) = false, want true", file.Name())
}
// Test with a non-existing file
exists = FileExists("non_existing_file.txt")
if exists {
t.Errorf("FileExists(%q) = true, want false", "non_existing_file.txt")
}
}

View File

@@ -0,0 +1,54 @@
package healthcheck
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
)
type HealthCheck interface {
SetStatus(status string)
GetStatus() string
HealthCheckHandler() gin.HandlerFunc
}
type healthCheck struct {
status string
sync sync.Mutex
}
func New() HealthCheck {
return &healthCheck{
status: "ok",
}
}
func (hc *healthCheck) SetStatus(status string) {
hc.sync.Lock()
defer hc.sync.Unlock()
hc.status = status
}
func (hc *healthCheck) GetStatus() string {
hc.sync.Lock()
defer hc.sync.Unlock()
return hc.status
}
func (hc *healthCheck) HealthCheckHandler() gin.HandlerFunc {
return func(c *gin.Context) {
switch hc.GetStatus() {
case "nok":
c.JSON(http.StatusInternalServerError, gin.H{
"status": hc.GetStatus(),
})
default:
c.JSON(http.StatusOK, gin.H{
"status": hc.GetStatus(),
})
}
}
}

View File

@@ -0,0 +1,131 @@
package healthcheck
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestHealthCheck_GetStatus(t *testing.T) {
var hc HealthCheck
type fields struct {
status string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test GetStatus with status ok",
fields: fields{
status: "ok",
},
want: "ok",
},
{
name: "Test GetStatus with status nok",
fields: fields{
status: "nok",
},
want: "nok",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
hc = &healthCheck{
status: tt.fields.status,
}
if got := hc.GetStatus(); got != tt.want {
t.Errorf("HealthCheck.GetStatus() = %v, want %v", got, tt.want)
}
})
}
}
func TestHealthCheck_SetStatus(t *testing.T) {
hc := New()
type args struct {
status string
}
tests := []struct {
name string
args args
want string
}{
{
name: "Test SetStatus with status ok",
args: args{
status: "ok",
},
want: "ok",
},
{
name: "Test SetStatus with status nok",
args: args{
status: "nok",
},
want: "nok",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
hc.SetStatus(tt.args.status)
if got := hc.GetStatus(); got != tt.want {
t.Errorf("HealthCheck.GetStatus() = %v, want %v", got, tt.want)
}
})
}
}
func TestHealthCheck_HealthCheckHandler(t *testing.T) {
r := gin.Default()
hc := New()
r.GET("/health", hc.HealthCheckHandler())
type args struct {
status string
}
tests := []struct {
name string
args args
want string
statusCode int
}{
{
name: "Test respond with status ok",
args: args{
status: "ok",
},
want: `{"status":"ok"}`,
statusCode: http.StatusOK,
},
{
name: "Test respond with status nok",
args: args{
status: "nok",
},
want: `{"status":"nok"}`,
statusCode: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
hc.SetStatus(tt.args.status)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/health", nil)
r.ServeHTTP(w, req)
if got := w.Code; got != tt.statusCode {
t.Errorf("HealthCheck response status code = %v, want %v", got, tt.statusCode)
}
if got := w.Body.String(); got != tt.want {
t.Errorf("HealthCheck response = %v, want %v", got, tt.want)
}
})
}
}

40
pkg/setup_https_server.go Normal file
View File

@@ -0,0 +1,40 @@
package pkg
import (
"errors"
"log"
"net/http"
"time"
)
func SetupHttpsServer(router http.Handler, cert, key, httpsPort, httpPort string, requestTimeout time.Duration) (server *http.Server) {
if FileExists(cert) && FileExists(key) {
server = &http.Server{
Addr: httpsPort,
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
go func() {
log.Println("Server starts at port ", httpsPort)
if err := server.ListenAndServeTLS(cert, key); err != nil && errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
} else {
server = &http.Server{
Addr: httpPort,
Handler: router,
ReadTimeout: requestTimeout * time.Second,
WriteTimeout: requestTimeout * time.Second,
}
go func() {
log.Println("Server starts at port ", httpPort)
if err := server.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
}
return server
}

29
pkg/setup_logger.go Normal file
View File

@@ -0,0 +1,29 @@
package pkg
import (
"fmt"
"io"
"log"
"os"
"time"
"github.com/gin-gonic/gin"
)
func SetupLogger(logToFileAndStd bool, logToFile bool) {
if logToFileAndStd || logToFile {
gin.DisableConsoleColor() // Disable Console Color, you don't need console color when writing the logs to file.
path := fmt.Sprintf("private/logs/%02dy_%02dm_%02dd_%02dh_%02dm_%02ds.log", time.Now().Year(), time.Now().Month(), time.Now().Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second())
logerror1 := os.MkdirAll("private/logs/", 0755)
f, logerror2 := os.Create(path)
if logerror1 != nil || logerror2 != nil {
log.Println("Cant log to file")
} else if logToFileAndStd {
gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
} else {
gin.DefaultWriter = io.MultiWriter(f)
}
}
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.SetOutput(gin.DefaultErrorWriter)
}