Created
November 2, 2024 13:05
-
-
Save roopeshsn/0185a6bf91243ed18fbf4e5a52ba02a0 to your computer and use it in GitHub Desktop.
Serving both HTTP and HTTPS (TLS) requests in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"sync" | |
) | |
func homeRouteHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path) | |
} | |
func main() { | |
var wg sync.WaitGroup | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", homeRouteHandler) | |
// HTTP Listener (without TLS) | |
httpPort := ":8083" | |
wg.Add(1) | |
go func() { | |
fmt.Printf("go-tls-server listening to HTTP requests on PORT %s \n", httpPort) | |
defer wg.Done() | |
if err := http.ListenAndServe(httpPort, mux); err != nil { | |
fmt.Println("HTTP server error:", err) | |
} | |
}() | |
// HTTPS Listener (with TLS) | |
httpsPort := ":8082" | |
cert := "localhost.crt" | |
privateKey := "localhost.key" | |
wg.Add(1) | |
go func() { | |
fmt.Printf("go-tls-server listening to HTTPS requests on PORT %s \n", httpsPort) | |
defer wg.Done() | |
if err := http.ListenAndServeTLS(httpsPort, cert, privateKey, mux); err != nil { | |
fmt.Println("HTTPS server error:", err) | |
} | |
}() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment