Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added network service - handler and receiver #403

Open
wants to merge 12 commits into
base: beckn-onix-v1.0-develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ web_modules/
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
**/.env
shared/constants/services.json


# Next.js build output
.next
Expand Down
30 changes: 30 additions & 0 deletions cmd/clientSideHandler/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"net/http"

"beckn-onix/cmd/clientSideHandler/src/config"
"beckn-onix/cmd/clientSideHandler/src/routes"
utils "beckn-onix/shared/utils"
)

func main() {
// Load environment variables
config.LoadEnv()

// Get server port
port := config.GetPort()

// Initialize router
mux := routes.InitializeRoutes()

// Start Pub/Sub Listener in a goroutine
// go handlers.SubscribeToMessages(config.GetSubscriptionID())

utils.Log.Println("Server started on", port)

// Start the HTTP server
if err := http.ListenAndServe(port, mux); err != nil {
utils.Log.Fatalln("Failed to start server on", port, err)
}
}
39 changes: 39 additions & 0 deletions cmd/clientSideHandler/src/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package config

import (
"beckn-onix/shared/utils"
"os"

"github.com/joho/godotenv"
)

// LoadEnv loads environment variables
func LoadEnv() {
if err := godotenv.Load(); err != nil {
utils.Log.Println("No .env file found, using system environment variables")
}
}

// GetPort retrieves the server port from environment variables
func GetPort() string {
port := os.Getenv("PORT")
if port == "" {
port = "8081" // Default port
}
return ":" + port
}

// GetProjectID retrieves the Google Cloud Project ID
func GetProjectID() string {
return os.Getenv("GOOGLE_CLOUD_PROJECT")
}

// GetSubscriptionID retrieves the Pub/Sub subscription ID
func GetSubscriptionID() string {
return os.Getenv("PUBSUB_SUBSCRIPTION_ID")

}

func GetTopicID() string {
return os.Getenv("PUBSUB_TOPIC_ID")
}
17 changes: 17 additions & 0 deletions cmd/clientSideHandler/src/handler/home.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package handlers

import (
"fmt"
"net/http"
)

// HomeHandler handles the home route
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Fprintf(w, "This is a GET request")
} else if r.Method == "POST" {
fmt.Fprintf(w, "This is a POST request")
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
14 changes: 14 additions & 0 deletions cmd/clientSideHandler/src/routes/routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package routes

import (
handlers "beckn-onix/cmd/clientSideHandler/src/handler"
"net/http"
)

func InitializeRoutes() *http.ServeMux {
mux := http.NewServeMux()

mux.HandleFunc("/", handlers.HomeHandler)

return mux
}
6 changes: 6 additions & 0 deletions cmd/clientSideReceiver/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
app_name: "clientSideReciever"
server_port: 8080
db_host: "localhost"
db_port: 5432
db_user: "username"
db_password: "password"
54 changes: 54 additions & 0 deletions cmd/clientSideReceiver/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package config

import (
"log"
"os"

"context"
"fmt"
"github.com/joho/godotenv"
"gopkg.in/yaml.v2" // For unmarshaling YAML
)

// Config struct captures all the necessary configuration
type Config struct {
AppName string `yaml:"app_name"`
ServerPort int `yaml:"server_port"`
DBHost string `yaml:"db_host"`
DBPort int `yaml:"db_port"`
DBUser string `yaml:"db_user"`
DBPassword string `yaml:"db_password"`
}

func InitConfig(ctx context.Context, path string) (*Config, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("could not open config file: %v", err)
}
defer file.Close()

// Unmarshal the YAML data
var config Config
decoder := yaml.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
return nil, fmt.Errorf("could not unmarshal config data: %v", err)
}

return &config, nil
}

func LoadEnv() {
err := godotenv.Load()
if err != nil {
log.Println("Warning: .env file not found, using system environment variables")
}
}

func GetPort() string {
port := os.Getenv("PORT")
if port == "" {
port = ":8080" // Default port
}
return port
}
29 changes: 29 additions & 0 deletions cmd/clientSideReceiver/handler/home.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package handlers

import (
"encoding/json"
"fmt"
"net/http"
)

type PublishRequest struct {
Message string `json:"message"`
}

// HomeHandler handles the home route
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
var req PublishRequest

// Parse JSON body
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}

w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Message recieved successfully")
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
45 changes: 45 additions & 0 deletions cmd/clientSideReceiver/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package main

import (
config "beckn-onix/cmd/clientSideReceiver/config"
handlers "beckn-onix/cmd/clientSideReceiver/handler"
utils "beckn-onix/shared/utils"
"context"
"flag"
"fmt"
"log"
"net/http"
)

func main() {

// Define the command-line flag for the YAML file path
configPath := flag.String("config", "config.yaml", "./config.yaml")
flag.Parse()

// Define the context (could be used for cancellation or timeouts)
ctx := context.Background()

// Load the configuration using InitConfig
configuration, err := config.InitConfig(ctx, *configPath)
if err != nil {
log.Fatalf("Error initializing config: %v", err)
}

// Use the config to initialize the server
fmt.Printf("App Name: %s\n", configuration.AppName)
fmt.Printf("Server Port: %d\n", configuration.ServerPort)
fmt.Printf("Database Host: %s\n", configuration.DBHost)
fmt.Printf("Database Port: %d\n", configuration.DBPort)
fmt.Printf("Database User: %s\n", configuration.DBUser)

port := fmt.Sprintf(":%d", configuration.ServerPort)

// Initialize router
http.HandleFunc("/", handlers.HomeHandler)

utils.Log.Info("Server started on", port)
if err := http.ListenAndServe(port, nil); err != nil {
utils.Log.Error("Server started on", port)
}
}
55 changes: 55 additions & 0 deletions cmd/networkSideHandler/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"fmt"
"net/http"
"os"
"gopkg.in/yaml.v2"

logger "beckn-onix/shared/utils"
)

type Config struct {
AppName string `yaml:"appName"`
Port int `yaml:"port"`
}

func main() {
cfg := loadConfig()
StartServer(cfg)
}

func StartServer(cfg *Config) {
http.HandleFunc("/", CreatePostHandler) // Fixed: Removed "POST /"

logger.Log.Info("Server is running on port: ", cfg.Port)
logger.Log.Error(http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), nil))
}

func loadConfig() *Config {

data, err := os.ReadFile("../../config/networkSideHandler-config.yaml")
if err != nil {
logger.Log.Error("error reading config file:", err)
}

var config Config

err = yaml.Unmarshal(data, &config)
if err != nil {
logger.Log.Error("error unmarshaling config:", err)
}

return &config
}


func CreatePostHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.WriteHeader(http.StatusOK)
}


71 changes: 71 additions & 0 deletions cmd/networkSideHandler/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package main

import (
"net/http"
"net/http/httptest"
"testing"
)

func TestLoadConfig(t *testing.T) {
tests := []struct {
name string
wantAppName string
wantPort int
err bool
}{
{
name: "failed - Invalid config",
wantAppName: "testNetworkSideHandler",
wantPort: 7071,
err: true,
},

{
name: "Success - Valid config",
wantAppName: "networkSideHandler",
wantPort: 9091,
err: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

config := loadConfig()

if config.AppName == tt.wantAppName && tt.err == true {
t.Errorf("%s: Expected appName: %s and port: %d, got appName: %s, port: %d", tt.name, tt.wantAppName, tt.wantPort, config.AppName, config.Port)
}

if config.AppName != tt.wantAppName && tt.err == false {
t.Errorf("%s: Expected appName: %s and port: %d, got appName: %s, port: %d", tt.name, tt.wantAppName, tt.wantPort, config.AppName, config.Port)
}
})
}
}

func TestCreatePostHandler(t *testing.T) {
go func () {
main()
}()
tests := []struct {
name string
method string
expectCode int
}{
{"Valid POST Request", http.MethodPost, http.StatusOK},
{"Invalid GET Request", http.MethodGet, http.StatusMethodNotAllowed},
{"Invalid PUT Request", http.MethodPut, http.StatusMethodNotAllowed},
{"Invalid DELETE Request", http.MethodDelete, http.StatusMethodNotAllowed},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(tt.method, "/", nil)
w := httptest.NewRecorder()
CreatePostHandler(w, req)
if w.Code != tt.expectCode {
t.Errorf("%s: Expected status %d, got %d", tt.name, tt.expectCode, w.Code)
}
})
}
}
Loading