This repository was archived by the owner on Nov 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
59 lines (47 loc) · 1.24 KB
/
server.go
File metadata and controls
59 lines (47 loc) · 1.24 KB
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
package main
import (
"io/ioutil"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
const (
requestBodyReadError = "Failed to read request body"
)
// GetRouter returns the Gin router.
func GetRouter(port string, dbConnection *DBConnection) *gin.Engine {
h := &TokenHandler{
dbConn: dbConnection,
}
r := gin.Default()
r.POST("/use_token", h.postUseToken)
r.GET("/test_get_token", h.getTestToken)
return r
}
// TokenHandler implements the handler functions for the API endpoints.
// It also holds the database connection that's used by the handler functions.
type TokenHandler struct {
dbConn *DBConnection
}
func (h *TokenHandler) postUseToken(c *gin.Context) {
body := c.Request.Body
data, err := ioutil.ReadAll(body)
if err != nil {
c.String(http.StatusBadRequest, requestBodyReadError)
return
}
valid, err := h.dbConn.checkAndRemoveToken(string(data))
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
c.Data(http.StatusOK, "text/plain", []byte(strconv.FormatBool(valid)))
}
func (h *TokenHandler) getTestToken(c *gin.Context) {
token, err := h.dbConn.createToken()
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
c.Data(http.StatusOK, "text/plain", []byte(token))
}