-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
42 lines (34 loc) · 899 Bytes
/
http.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
package main
import (
"encoding/json"
"log"
"mcauth/codes"
"net/http"
"strconv"
)
func setupHttpServer() {
http.HandleFunc("GET /retrieve/{code}", onRetrieve)
log.Fatalln(http.ListenAndServe(":8080", nil))
}
func onRetrieve(w http.ResponseWriter, r *http.Request) {
code, err := strconv.Atoi(r.PathValue("code"))
if err != nil {
sendJson(w, map[string]string{"error": codes.ErrInvalidCode.Error()}, http.StatusBadRequest)
return
}
id, err := codes.Retrieve(code)
if err != nil {
sendJson(w, map[string]string{"error": err.Error()}, http.StatusBadRequest)
return
}
sendJson(w, map[string]string{"uuid": id.String()}, http.StatusOK)
}
func sendJson(w http.ResponseWriter, value any, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
err := json.NewEncoder(w).Encode(value)
if err != nil {
log.Println(err.Error())
return
}
}