-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
38 lines (30 loc) · 1.04 KB
/
helpers.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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/golang-jwt/jwt/v4"
)
func RespondWithJSON(w http.ResponseWriter, r *http.Request,statuscode int,response interface{}) {
w.Header().Set("Content-Type","application/json")
w.WriteHeader(statuscode)
json.NewEncoder(w).Encode(response)
}
func RespondWithError(w http.ResponseWriter,r *http.Request,statuscode int, message string) {
w.Header().Set("Content-Type","application/json")
w.WriteHeader(statuscode)
json.NewEncoder(w).Encode(ErrorResponse{statuscode,message})
}
func GenerateJWTToken(username string) (string,error){
expirationTime := time.Now().Add(30 * time.Minute)
claims := &Claims{
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now()),
ExpiresAt: jwt.NewNumericDate(expirationTime),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(GetJWTSecretKey())
return tokenString,err
}