-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
50bce80
commit 38eb52a
Showing
1 changed file
with
86 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
package main | ||
|
||
import ( | ||
"log" | ||
"net/http" | ||
"net/http/httputil" | ||
"net/url" | ||
) | ||
|
||
type Config struct { | ||
ListenAddr string | ||
TargetURL string | ||
AuthServiceURL string | ||
} | ||
|
||
type EntryPoint struct { | ||
config *Config | ||
proxy *httputil.ReverseProxy | ||
authClient *http.Client | ||
} | ||
|
||
func NewEntryPoint(config *Config) (*EntryPoint, error) { | ||
targetURL, err := url.Parse(config.TargetURL) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return &EntryPoint{ | ||
config: config, | ||
proxy: httputil.NewSingleHostReverseProxy(targetURL), | ||
authClient: &http.Client{}, | ||
}, nil | ||
} | ||
|
||
func (ep *EntryPoint) verifyAuth(token string) (bool, error) { | ||
req, err := http.NewRequest("POST", ep.config.AuthServiceURL, nil) | ||
if err != nil { | ||
return false, err | ||
} | ||
|
||
req.Header.Set("Authorization", token) | ||
resp, err := ep.authClient.Do(req) | ||
if err != nil { | ||
return false, err | ||
} | ||
defer resp.Body.Close() | ||
|
||
return resp.StatusCode == http.StatusOK, nil | ||
} | ||
|
||
func (ep *EntryPoint) ProxyHandler(w http.ResponseWriter, r *http.Request) { | ||
|
||
token := r.Header.Get("Authorization") | ||
|
||
|
||
authorized, err := ep.verifyAuth(token) | ||
if err != nil { | ||
http.Error(w, "Authorization service error", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
if !authorized { | ||
http.Error(w, "Unauthorized", http.StatusUnauthorized) | ||
return | ||
} | ||
|
||
|
||
ep.proxy.ServeHTTP(w, r) | ||
} | ||
|
||
func main() { | ||
config := &Config{ | ||
ListenAddr: ":8080", | ||
TargetURL: "http://target-service:8000", | ||
AuthServiceURL: "http://auth-service:8001/verify", | ||
} | ||
|
||
entryPoint, err := NewEntryPoint(config) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
http.HandleFunc("/", entryPoint.ProxyHandler) | ||
log.Printf("Starting entry point on %s", config.ListenAddr) | ||
log.Fatal(http.ListenAndServe(config.ListenAddr, nil)) | ||
} |