aboutsummaryrefslogtreecommitdiff
path: root/cmd/http/main.go
diff options
context:
space:
mode:
authorAlex <alex@scerba.org>2024-05-04 17:28:37 -0400
committerAlex Scerba <alex@scerba.org>2024-08-15 22:54:25 -0500
commit811c9bb2f7358ff094fe13deb6d961088baa2d8f (patch)
tree694010fbc71c9ff67cee28f6da1447290e627afe /cmd/http/main.go
parentd9fc74778ef86b02f0a743821263db8873417294 (diff)
Add Go webserver.
Diffstat (limited to 'cmd/http/main.go')
-rw-r--r--cmd/http/main.go83
1 files changed, 83 insertions, 0 deletions
diff --git a/cmd/http/main.go b/cmd/http/main.go
new file mode 100644
index 0000000..828b9d8
--- /dev/null
+++ b/cmd/http/main.go
@@ -0,0 +1,83 @@
+package main
+
+import (
+ "flag"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+)
+
+var (
+ fullchain = "/etc/letsencrypt/live/alexscerba.com/fullchain.pem"
+ privkey = "/etc/letsencrypt/live/alexscerba.com/privkey.pem"
+)
+
+type application struct {
+ errorLog *log.Logger
+ infoLog *log.Logger
+}
+
+func (app *application) httpsRedirect(w http.ResponseWriter, req *http.Request) {
+ // remove/add not default ports from req.Host
+ target := "https://" + req.Host + req.URL.Path
+ if len(req.URL.RawQuery) > 0 {
+ target += "?" + req.URL.RawQuery
+ }
+ app.infoLog.Printf("redirect to: %s", target)
+ http.Redirect(w, req, target,
+ // see comments below and consider the codes 308, 302, or 301
+ http.StatusMovedPermanently)
+}
+
+func (app *application) wwwRedirect(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasPrefix(r.Host, "www.") {
+ http.Redirect(w, r, "https://www."+r.Host+r.RequestURI, 302)
+ return
+ }
+
+ h.ServeHTTP(w, r)
+ })
+}
+
+func main() {
+ addr := flag.String("addr", ":4002", "HTTP Network Address")
+ flag.Parse() // required before flag is used
+
+ infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
+ errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
+
+ app := &application{
+ errorLog: errorLog,
+ infoLog: infoLog,
+ }
+
+ mux := http.NewServeMux()
+
+ fs := http.FileServer(http.Dir("./static"))
+ mux.Handle("/static/", http.StripPrefix("/static/", fs))
+
+ mux.HandleFunc("/faq", app.faq)
+ mux.HandleFunc("/faq/", app.faq)
+ mux.HandleFunc("/about", app.about)
+ mux.HandleFunc("/about/", app.about)
+ mux.HandleFunc("/gallery", app.gallery)
+ mux.HandleFunc("/gallery/", app.gallery)
+ mux.HandleFunc("/blog", app.blog)
+ mux.HandleFunc("/blog/", app.blog)
+ mux.HandleFunc("/", app.home)
+
+ if *addr == ":443" {
+ www := app.wwwRedirect(mux)
+
+ infoLog.Printf("Starting TLS server on %s...\n", *addr)
+ go http.ListenAndServe(":80", www)
+ err := http.ListenAndServeTLS(*addr, fullchain, privkey, gzipHandler(www))
+ log.Fatal(err)
+ } else {
+ infoLog.Printf("Starting server on %s...\n", *addr)
+ err := http.ListenAndServe(*addr, gzipHandler(mux))
+ log.Fatal(err)
+ }
+}