Last active
August 20, 2019 17:52
-
-
Save rogerwelin/7dc9bcf7e2d4a92ad1a3fcb367df41ac to your computer and use it in GitHub Desktop.
auth server
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" | |
| "log" | |
| "net/http" | |
| "time" | |
| ) | |
| // All requests will go here first to see if client is authenticated | |
| func authHandler(w http.ResponseWriter, r *http.Request) { | |
| authToken := r.Header.Get("X-Auth-Token") | |
| // no auth token - respond unathorized | |
| if authToken == "" { | |
| log.Println("unathorized access") | |
| w.WriteHeader(401) | |
| return | |
| } | |
| // hardcoded example - simulate fetching from auth storage | |
| if authToken != "abc123" { | |
| log.Println("invalid auth token, unathorized") | |
| w.WriteHeader(401) | |
| return | |
| } | |
| // client is authenticated - set header to pass downstream | |
| // to let services know where the request originated from | |
| log.Println("adding client header") | |
| w.Header().Set("X-Client-ID", "acmecorp") | |
| w.WriteHeader(200) | |
| } | |
| // only authorized access will hit this endpoint | |
| func helloHandler(w http.ResponseWriter, r *http.Request) { | |
| client := r.Header.Get("X-Client-ID") | |
| fmt.Fprintln(w, "you're authenticated "+client) | |
| } | |
| func main() { | |
| addr := "0.0.0.0:5000" | |
| router := http.NewServeMux() | |
| router.HandleFunc("/", helloHandler) | |
| router.HandleFunc("/auth", authHandler) | |
| srv := &http.Server{ | |
| Addr: addr, | |
| WriteTimeout: time.Second * 5, | |
| ReadTimeout: time.Second * 5, | |
| Handler: router, | |
| } | |
| log.Fatal(srv.ListenAndServe()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment