grepfood-demo/server/main.go

55 lines
1.1 KiB
Go

package main
import (
"log"
"net/http"
"encoding/json"
"os"
"github.com/golang-jwt/jwt"
"time"
)
func GenerateJwt(username string) (string, error) {
token := jwt.New(jwt.SigningMethodEdDSA)
claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(10 * time.Minute)
claims["authorized"] = true
claims["user"] = username
tokenString, err := token.SignedString(os.Getenv("GREPFOOD_JWT_SECRET"))
if err != nil {
return "", err
}
return tokenString, nil
}
func WriteJson(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
jsonData, err := json.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(jsonData)
}
func handleVersion(w http.ResponseWriter, r *http.Request) {
version := struct {Version string `json:version`} {
Version: "0.1.0-demo",
}
WriteJson(w, version)
}
func main() {
http.HandleFunc("/version", handleVersion)
http.Handle("/", http.FileServer(http.Dir("./static")))
log.Fatal(http.ListenAndServe(os.Getenv("GREPFOOD_SYNCSERVER_PORT"), nil))
}