Tuesday, April 29, 2025

Go autocert HTTPS web server

Making "production ready" web serve in GoLang takes a few lines of code only.

Making "secure" web server with HTTPS is just a few more lines of code.
That requires providing TLS cert keys.

Even obtaining free cert keys is possible by using "autocert" go package.
with "Let's Encrypt" free certs provider.

ssl - How to set up Let's Encrypt for a Go server application - Stack Overflow

Early renewal with autocert - Help - Let's Encrypt Community Support

autocert package - golang.org/x/crypto/acme/autocert - Go Packages

basic, configurable, Go files web server

go run server.go
go run server.go -dir=/path/to/your/files
go run server.go -port=3000
go run server.go -dir=/path/to/your/files -port=3000


package main

import (
    "flag"
    "fmt"
    "net/http"
    "os"
)

func main() {
    // Define command line flags
    dirPath := flag.String("dir", ".", "Directory path to serve files from")
    port := flag.String("port", "8080", "Port to run the server on")

    // Parse command line arguments
    flag.Parse()

    // Use specified directory
    staticDir := *dirPath

    // Verify the directory exists
    if _, err := os.Stat(staticDir); os.IsNotExist(err) {
        fmt.Printf("Error: Directory '%s' does not exist\n", staticDir)
        os.Exit(1)
    }

    // Create a file server handler for the specified directory
    fileServer := http.FileServer(http.Dir(staticDir))

    // Handle all requests by trying to serve a file
    http.Handle("/", fileServer)

    // Format the address with the port
    addr := ":" + *port

    // Start the server
    fmt.Printf("Server starting on port %s...\n", *port)
    fmt.Printf("Serving files from: %s\n", staticDir)
    fmt.Printf("Access at http://localhost%s\n", addr)

    err := http.ListenAndServe(addr, nil)
    if err != nil {
        fmt.Printf("Error starting server: %s\n", err)
    }
}


How To Make an HTTP Server in Go | DigitalOcean

No comments: