First, ensure you have Gin installed:
bash
Copy code
go get -u github.com/gin-gonic/gin
Here's the file server implementation:
go
Copy code
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
// Define your secret token
const secretToken = "your_secret_token"
// AuthMiddleware is a middleware to authenticate requests
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Extract the token from the Authorization header
token := c.GetHeader("Authorization")
// Check if the token is valid
if token != "Bearer "+secretToken {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
// Token is valid, continue processing
c.Next()
}
}
func main() {
// Initialize Gin
r := gin.Default()
// Apply the authentication middleware to all routes
r.Use(AuthMiddleware())
// Define a route to serve files
r.Static("/files", "./files")
// Start the server
log.Printf("Server started. Listening on port 8080...")
r.Run(":8080")
}
Ensure you have a directory named files in the same directory as your Go file, and place the files you want to serve inside it.
Now, let's create a Dockerfile to containerize our application:
Dockerfile
Copy code
# Use the official Golang image as base
FROM golang:alpine AS builder
# Set the current working directory inside the container
WORKDIR /app
# Copy the local package files to the container's workspace
COPY . .
# Build the Go app
RUN go build -o file-server .
# Start a new stage from scratch
FROM alpine:latest
# Copy the binary from the builder stage to the new stage
COPY --from=builder /app/file-server /app/file-server
# Expose port 8080 to the outside world
EXPOSE 8080
# Command to run the executable
CMD ["/app/file-server"]
Finally, let's create a docker-compose.yml file to define and run our Docker services:
yaml
Copy code
version: '3'
services:
file-server:
build:
context: .
ports:
- "8080:8080"
volumes:
- ./files:/app/files
Now, you can run your file server and Dockerize it using Docker Compose:
bash
Copy code
docker-compose up --build
Your file server will now be running in a Docker container, and you can access it at http://localhost:8080/files. Remember to replace "your_secret_token" with your actual secret token.