-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.go
85 lines (72 loc) · 1.86 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"io"
"net/http"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
cognito "github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/br4in3x/golang-cognito-example/app"
)
// Stream responds with static HTML file
func Stream(w http.ResponseWriter, r *http.Request) {
// Redirect all requests to root to index.html
if r.URL.Path == "/" {
r.URL.Path = "/index"
}
path := fmt.Sprintf("./static%s.html", r.URL.Path)
html, err := os.Open(path)
defer html.Close()
if err != nil {
http.Error(w, fmt.Sprintf("File %s not found", path), http.StatusNotFound)
return
}
w.Header().Set("Content-type", "text/html")
io.Copy(w, html)
}
// Call routes POST requests
func Call(a *app.App, w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/login":
a.Login(w, r)
case "/otp":
a.OTP(w, r)
case "/register":
a.Register(w, r)
case "/username":
a.Username(w, r)
default:
http.Error(w, fmt.Sprintf("Handler for POST %s not found", r.URL.Path), http.StatusNotFound)
}
return
}
func main() {
conf := &aws.Config{Region: aws.String("us-east-1")}
sess, err := session.NewSession(conf)
if err != nil {
panic(err)
}
example := app.App{
CognitoClient: cognito.New(sess),
UserPoolID: os.Getenv("COGNITO_USER_POOL_ID"),
AppClientID: os.Getenv("COGNITO_APP_CLIENT_ID"),
AppClientSecret: os.Getenv("COGNITO_APP_CLIENT_SECRET"),
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
// Respond with static file
Stream(w, r)
case http.MethodPost:
// Handle html form submission
Call(&example, w, r)
}
})
addr := fmt.Sprintf(":%s", os.Getenv("PORT"))
fmt.Printf("Starting Cognito Example on localhost%s...", addr)
err = http.ListenAndServe(addr, nil)
if err != nil {
panic(err.Error())
}
}