Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
publish_output/
hello-web-server/hello-web-server
19 changes: 19 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
FROM alpine:latest

# Install CA certificates for HTTPS connections
RUN apk --no-cache add ca-certificates

# Set working directory
WORKDIR /app

# Copy the compiled binary
COPY publish_output/hello-web-server /app/

# Set execute permissions on the binary
RUN chmod +x /app/hello-web-server

# Expose port 8080
EXPOSE 8080

# Run the application
CMD ["/app/hello-web-server"]
43 changes: 43 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
.PHONY: all build prepare-artifacts display-artifacts clean run test

# Default target
all: build prepare-artifacts display-artifacts

# Build the Go project
build:
@echo "Building Go web server..."
cd hello-web-server && CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o hello-web-server -v .

# Prepare artifacts for publishing
prepare-artifacts:
@echo "Preparing artifacts..."
mkdir -p publish_output
cp hello-web-server/hello-web-server publish_output/

# Display artifact contents
display-artifacts:
@echo "Artifact contents:"
ls -lh publish_output/

# Run the web server locally
run:
@echo "Running web server..."
cd hello-web-server && go run main.go

# Test the web server endpoints
test:
@echo "Testing endpoints (server must be running)..."
@echo "Testing root endpoint:"
curl -s http://localhost:8080/ | jq . || echo "Server not running or jq not installed"
@echo "\nTesting hello endpoint:"
curl -s http://localhost:8080/api/hello | jq . || echo "Server not running or jq not installed"
@echo "\nTesting hello with name:"
curl -s http://localhost:8080/api/hello?name=Developer | jq . || echo "Server not running or jq not installed"
@echo "\nTesting health endpoint:"
curl -s http://localhost:8080/health | jq . || echo "Server not running or jq not installed"

# Clean up build artifacts and publish_output
clean:
@echo "Cleaning up..."
rm -rf publish_output
rm -f hello-web-server/hello-web-server
134 changes: 134 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,136 @@
# sample-test
hands on repo to test everything

## Hello Web Server

A simple Go web server application demonstrating REST API endpoints, JSON responses, and containerization.

### Features

- **Simple HTTP Web Server**: Built using Go's standard `net/http` package
- **REST API Endpoints**:
- `GET /` - Welcome message
- `GET /api/hello` - Hello greeting (supports `?name=` query parameter)
- `GET /health` - Health check with uptime information
- **JSON Responses**: All endpoints return JSON formatted responses
- **Request Logging**: Logs all incoming requests with timestamps
- **Docker Support**: Containerized application ready for deployment
- **Make Automation**: Makefile for easy building, testing, and deployment

### Project Structure

```
hello-web-server/
├── main.go # Main application with HTTP handlers
└── go.mod # Go module definition

Dockerfile # Docker image configuration
Makefile # Build automation
```

### Getting Started

#### Prerequisites

- Go 1.24 or later
- Docker (optional, for containerization)
- curl (for testing)

#### Building the Project

```bash
# Build the project
make build

# Prepare artifacts for deployment
make prepare-artifacts
```

#### Running the Server

```bash
# Run locally
make run

# Or run directly with Go
cd hello-web-server && go run main.go
```

The server will start on `http://localhost:8080`

#### Testing the Endpoints

```bash
# Test all endpoints (server must be running)
make test

# Or test manually:
curl http://localhost:8080/
curl http://localhost:8080/api/hello
curl http://localhost:8080/api/hello?name=Developer
curl http://localhost:8080/health
```

#### Docker Deployment

```bash
# Build the binary
make build

# Prepare artifacts
make prepare-artifacts

# Build Docker image
docker build -t hello-web-server:latest .

# Run the container
docker run -p 8080:8080 hello-web-server:latest
```

#### Clean Up

```bash
make clean
```

### Differences from hello_go

This project is similar in structure to the `hello_go` project but takes a different approach:

| Aspect | hello_go | hello-web-server |
|--------|----------|------------------|
| **Purpose** | Structured logging demonstration | HTTP web server with REST API |
| **Libraries** | dazl (third-party logging) | Standard library (net/http) |
| **Main Feature** | Various log levels and formats | HTTP endpoints with JSON responses |
| **Configuration** | YAML logging config | No external config needed |
| **Output** | Console logs | HTTP responses + request logs |
| **Use Case** | Learning structured logging | Building simple web services |

### Example Responses

**GET /**
```json
{
"message": "Welcome to Hello Web Server! Visit /api/hello for a greeting.",
"status": "success",
"timestamp": "2026-02-12T09:08:00Z"
}
```

**GET /api/hello?name=Developer**
```json
{
"message": "Hello, Developer!",
"status": "success",
"timestamp": "2026-02-12T09:08:00Z"
}
```

**GET /health**
```json
{
"status": "healthy",
"uptime": "5m30s",
"timestamp": "2026-02-12T09:08:00Z"
}
```
3 changes: 3 additions & 0 deletions hello-web-server/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/DevipriyaS17/hello-web-server

go 1.24
99 changes: 99 additions & 0 deletions hello-web-server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package main

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

type Response struct {
Message string `json:"message"`
Status string `json:"status"`
Timestamp time.Time `json:"timestamp"`
}

type HealthResponse struct {
Status string `json:"status"`
Uptime string `json:"uptime"`
Timestamp time.Time `json:"timestamp"`
}

var startTime time.Time

func init() {
startTime = time.Now()
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Received %s request to %s from %s", r.Method, r.URL.Path, r.RemoteAddr)

response := Response{
Message: "Welcome to Hello Web Server! Visit /api/hello for a greeting.",
Status: "success",
Timestamp: time.Now(),
}

w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Printf("Error encoding JSON response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Received %s request to %s from %s", r.Method, r.URL.Path, r.RemoteAddr)

name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}

response := Response{
Message: fmt.Sprintf("Hello, %s!", name),
Status: "success",
Timestamp: time.Now(),
}

w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Printf("Error encoding JSON response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Health check from %s", r.RemoteAddr)

uptime := time.Since(startTime)

response := HealthResponse{
Status: "healthy",
Uptime: uptime.String(),
Timestamp: time.Now(),
}

w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Printf("Error encoding JSON response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}

func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/api/hello", helloHandler)
http.HandleFunc("/health", healthHandler)

port := ":8080"
log.Printf("Starting Hello Web Server on port %s", port)
log.Printf("Endpoints:")
log.Printf(" - GET / : Welcome message")
log.Printf(" - GET /api/hello : Hello endpoint (try ?name=YourName)")
log.Printf(" - GET /health : Health check")

if err := http.ListenAndServe(port, nil); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}