Skip to content

Commit

Permalink
golang .env e middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
EricLau1 committed Apr 2, 2019
1 parent d8e5062 commit fcf6fc8
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions go-env/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
APP_PORT=:9000
SECRET_MESSAGE=mindawakebodyasleep
27 changes: 27 additions & 0 deletions go-env/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"fmt"
"log"
"os"
"net/http"
"github.com/joho/godotenv"
)

func main() {
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
port := os.Getenv("APP_PORT")
message := os.Getenv("SECRET_MESSAGE")
if port == "" {
port = ":3000"
}
fmt.Println("Running on port", port)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(message))
})
log.Fatal(http.ListenAndServe(port, nil))
}

29 changes: 29 additions & 0 deletions go-middleware/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package main

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

func handler(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("Hello World!"))
if err != nil {
log.Fatal(err)
}
}

func exampleMiddleware(handler http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.Proto, r.Host, r.URL, time.Since(time.Now()))
handler.ServeHTTP(w, r)
})
}

func main() {
fmt.Println("Running...")
http.HandleFunc("/", exampleMiddleware(handler))
http.Handle("/favicon.ico", http.NotFoundHandler())
log.Fatal(http.ListenAndServe(":3000", nil))
}

0 comments on commit fcf6fc8

Please sign in to comment.