probo/server/main.go

242 lines
5.2 KiB
Go
Raw Normal View History

2023-12-05 22:11:08 +01:00
package main
import (
"encoding/json"
2023-12-12 09:21:55 +01:00
"io"
2023-12-11 09:32:50 +01:00
"log"
2023-12-05 22:11:08 +01:00
"math/rand"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"text/template"
"git.andreafazzi.eu/andrea/probo/models"
2023-12-12 09:21:55 +01:00
"git.andreafazzi.eu/andrea/probo/store"
2023-12-11 09:32:50 +01:00
"git.andreafazzi.eu/andrea/probo/store/file"
2023-12-05 22:11:08 +01:00
)
2023-12-11 09:32:50 +01:00
var (
DefaultDataDir = "data"
DefaultSessionDir = "sessions"
2023-12-12 09:21:55 +01:00
DefaultResponseDir = "responses"
2023-12-11 09:32:50 +01:00
DefaultTemplateDir = "templates"
DefaultStaticDir = "static"
)
type Config struct {
SessionDir string
2023-12-12 09:21:55 +01:00
ResponseDir string
2023-12-11 09:32:50 +01:00
TemplateDir string
StaticDir string
}
2023-12-05 22:11:08 +01:00
2023-12-11 09:32:50 +01:00
type ExamTemplateData struct {
*models.Exam
SessionID string
}
type Server struct {
2023-12-12 09:21:55 +01:00
config *Config
mux *http.ServeMux
2023-12-11 09:32:50 +01:00
2023-12-12 09:21:55 +01:00
sessionFileStore *file.SessionFileStore
responseFileStore *file.ResponseFileStore
2023-12-11 09:32:50 +01:00
}
func GetDefaultTemplateDir() string {
return DefaultTemplateDir
}
func GetDefaultStaticDir() string {
return DefaultStaticDir
}
2023-12-12 09:21:55 +01:00
func GetDefaultSessionDir() string {
return filepath.Join(DefaultDataDir, DefaultSessionDir)
}
func GetDefaultResponseDir() string {
return filepath.Join(DefaultDataDir, DefaultResponseDir)
}
2023-12-11 09:32:50 +01:00
2023-12-12 09:21:55 +01:00
func NewServer(config *Config) (*Server, error) {
2023-12-11 09:32:50 +01:00
_, err := os.Stat(config.SessionDir)
if err != nil {
return nil, err
2023-12-05 22:11:08 +01:00
}
2023-12-11 09:32:50 +01:00
_, err = os.Stat(config.TemplateDir)
if err != nil {
return nil, err
}
_, err = os.Stat(config.StaticDir)
if err != nil {
return nil, err
}
2023-12-12 09:21:55 +01:00
sStore, err := file.NewSessionFileStore(
&file.FileStoreConfig[*models.Session, *store.SessionStore]{
FilePathConfig: file.FilePathConfig{Dir: config.SessionDir, FilePrefix: "session", FileSuffix: ".json"},
IndexDirFunc: file.DefaultIndexDirFunc[*models.Session, *store.SessionStore],
CreateEntityFunc: func() *models.Session {
return &models.Session{}
},
},
)
if err != nil {
return nil, err
}
rStore, err := file.NewResponseFileStore(
&file.FileStoreConfig[*models.Response, *store.ResponseStore]{
FilePathConfig: file.FilePathConfig{Dir: config.ResponseDir, FilePrefix: "response", FileSuffix: ".json"},
IndexDirFunc: file.DefaultIndexDirFunc[*models.Response, *store.ResponseStore],
CreateEntityFunc: func() *models.Response {
return &models.Response{}
},
},
)
if err != nil {
return nil, err
}
rStore.FilePathConfig = file.FilePathConfig{
Dir: config.ResponseDir,
FilePrefix: "response",
FileSuffix: ".json",
}
2023-12-11 09:32:50 +01:00
s := &Server{
config,
http.NewServeMux(),
2023-12-12 09:21:55 +01:00
sStore,
rStore,
2023-12-11 09:32:50 +01:00
}
s.mux.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir(config.StaticDir))))
s.mux.HandleFunc("/create", s.createExamSessionHandler)
s.mux.HandleFunc("/", s.getExamHandler)
return s, nil
}
func NewDefaultServer() (*Server, error) {
return NewServer(&Config{
SessionDir: GetDefaultSessionDir(),
2023-12-12 09:21:55 +01:00
ResponseDir: GetDefaultResponseDir(),
2023-12-11 09:32:50 +01:00
TemplateDir: GetDefaultTemplateDir(),
StaticDir: GetDefaultStaticDir(),
})
2023-12-05 22:11:08 +01:00
}
2023-12-11 09:32:50 +01:00
func (s *Server) createExamSessionHandler(w http.ResponseWriter, r *http.Request) {
2023-12-12 09:21:55 +01:00
session := new(models.Session)
data, err := io.ReadAll(r.Body)
2023-12-05 22:11:08 +01:00
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
2023-12-12 09:21:55 +01:00
err = session.Unmarshal(data)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
2023-12-05 22:11:08 +01:00
2023-12-12 09:21:55 +01:00
memorySession, err := s.sessionFileStore.Create(session)
2023-12-05 22:11:08 +01:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2023-12-12 09:21:55 +01:00
response := map[string]string{"id": memorySession.ID}
2023-12-05 22:11:08 +01:00
json.NewEncoder(w).Encode(response)
}
2023-12-11 09:32:50 +01:00
func (s *Server) getExamHandler(w http.ResponseWriter, r *http.Request) {
2023-12-05 22:11:08 +01:00
urlParts := strings.Split(r.URL.Path, "/")
2023-12-12 09:21:55 +01:00
sessionID := urlParts[1]
2023-12-05 22:11:08 +01:00
token := urlParts[2]
2023-12-12 09:21:55 +01:00
session, err := s.sessionFileStore.Read(sessionID)
2023-12-05 22:11:08 +01:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2023-12-12 09:21:55 +01:00
exam := session.Exams[token]
2023-12-05 22:11:08 +01:00
2023-12-11 09:32:50 +01:00
if r.Method == "GET" {
w.Header().Set("Content-Type", "text/html")
tplData, err := os.ReadFile(filepath.Join(GetDefaultTemplateDir(), "exam.tpl"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl := template.Must(template.New("exam").Parse(string(tplData)))
2023-12-12 09:21:55 +01:00
err = tmpl.Execute(w, ExamTemplateData{exam, session.ID})
2023-12-11 09:32:50 +01:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if r.Method == "POST" {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
2023-12-12 09:21:55 +01:00
parts := strings.Split(r.FormValue("answer"), "_")
_, err = s.responseFileStore.Create(&models.Response{
QuestionID: parts[0],
AnswerID: parts[1],
})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
2023-12-11 09:32:50 +01:00
w.Header().Set("Content-Type", "text/html")
2023-12-12 09:21:55 +01:00
if parts[1] == exam.Quizzes[0].Correct.ID {
2023-12-11 09:32:50 +01:00
w.Write([]byte("<p>Corretto!</p>"))
return
}
w.Write([]byte("<p>Errato!</p>"))
2023-12-05 22:11:08 +01:00
return
}
}
2023-12-11 09:32:50 +01:00
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mux.ServeHTTP(w, r)
}
func generateRandomID() string {
id := ""
for i := 0; i < 6; i++ {
id += strconv.Itoa(rand.Intn(9) + 1)
}
return id
}
2023-12-05 22:11:08 +01:00
func main() {
2023-12-11 09:32:50 +01:00
server, err := NewDefaultServer()
if err != nil {
panic(err)
}
2023-12-05 22:11:08 +01:00
2023-12-11 09:32:50 +01:00
log.Println("Probo server started.", "Config", server.config)
http.ListenAndServe(":8080", server)
2023-12-05 22:11:08 +01:00
}