-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
75 lines (62 loc) · 1.57 KB
/
auth.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
package main
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"html/template"
)
type LoginForm struct {
Username string `json:"username"`
Password string `json:"password"`
}
type AuthResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
}
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("templates/*.html"))
}
func AuthHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var form LoginForm
err := json.NewDecoder(r.Body).Decode(&form)
if err != nil {
log.Printf("Error decoding login form: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
data := bytes.NewBuffer(nil)
json.NewEncoder(data).Encode(form)
resp, err := http.Post("http://api.accentvoice.com/api/auth/0.1/login", "application/json", data)
if err != nil {
log.Printf("Error contacting auth service: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading response body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var authResp AuthResponse
err = json.Unmarshal(body, &authResp)
if err != nil {
log.Printf("Error unmarshaling response: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if authResp.Success {
tpl.ExecuteTemplate(w, "main_page.html", nil)
} else {
tpl.ExecuteTemplate(w, "login.html", authResp)
}
}
func main() {
router := httprouter.New()
router.POST("/auth", AuthHandler)
log.Fatal(http.ListenAndServe(":8080", router))
}