瀏覽代碼

refactoring

Christian Marian - Work Dell 3 周之前
父節點
當前提交
0e461b4645

+ 2 - 1
cmds/webservice/bin/mynotes_cfg.json

@@ -1,4 +1,5 @@
 {
   "srvhost": "0.0.0.0",
-  "srvport": "3000"
+  "srvport": "3000",
+  "notes_directory":"notes_folder"
 }

二進制
cmds/webservice/bin/templates/Untitled.png


+ 1 - 11
cmds/webservice/bin/templates/edit_notes.tmpl

@@ -1,14 +1,4 @@
-<!DOCTYPE html>
-<html lang="ro">
-
-<head>
-  <meta charset="UTF-8">
-  <meta name="viewport" content="width=device-width, initial-scale=1.0">
-  <link rel="icon" type="image/png" href="/favicon.png">
-  <title>Editează notița</title>
-  <script src="https://cdn.tailwindcss.com"></script>
-</head>
-
+{{showFile "templates/section/head.tmpl"}}
 <body class="bg-[#0b0d12] text-white font-sans min-h-screen">
   <div class="max-w-4xl mx-auto px-6 py-10">
 

+ 1 - 9
cmds/webservice/bin/templates/error.tmpl

@@ -1,12 +1,4 @@
-<!DOCTYPE html>
-<html lang="ro">
-
-<head>
-  <meta charset="UTF-8">
-  <meta name="viewport" content="width=device-width, initial-scale=1.0">
-  <title>Eroare</title>
-  <script src="https://cdn.tailwindcss.com"></script>
-</head>
+{{showFile "templates/section/head.tmpl"}}
 
 <body class="bg-[#0b0d12] text-white font-sans min-h-screen flex items-center justify-center">
 

二進制
cmds/webservice/bin/templates/favicon.webp


+ 1 - 3
cmds/webservice/bin/templates/index.html

@@ -1,14 +1,12 @@
 <!DOCTYPE html>
 <html lang="ro">
-
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
-  <link rel="icon" type="image/png" href="/favicon.png">
+  <link rel="icon" type="image/webp" href="/favicon.webp">
   <title>MyNotes</title>
   <script src="https://cdn.tailwindcss.com"></script>
 </head>
-
 <body class="bg-[#0b0d12] text-white font-sans">
   <div class="min-h-screen flex items-center justify-center p-6">
     <div class="w-full max-w-2xl">

+ 6 - 11
cmds/webservice/bin/templates/list_notes.tmpl

@@ -1,13 +1,4 @@
-<!DOCTYPE html>
-<html lang="ro">
-
-<head>
-  <meta charset="UTF-8">
-  <title>Notițe</title>
-  <link rel="icon" type="image/png" href="/favicon.png">
-  <script src="https://cdn.tailwindcss.com"></script>
-</head>
-
+{{showFile "templates/section/head.tmpl"}}
 <body class="bg-[#0b0d12] text-white font-sans min-h-screen">
   <div class="max-w-5xl mx-auto px-6 py-10">
 
@@ -82,5 +73,9 @@
     </div>
   </div>
 
+  
 </div>
-{{end}}
+{{end}}
+{{range $val:= (genSeriesInt 50 10) }}
+  {{$val}},
+  {{end}}

+ 2 - 9
cmds/webservice/bin/templates/notita.tmpl

@@ -1,11 +1,4 @@
-<!DOCTYPE html>
-<html lang="ro">
-<head>
-    <meta charset="UTF-8">
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <link rel="icon" type="image/png" href="/favicon.png">
-    <title>{{.Titlu}}</title>
-    <script src="https://cdn.tailwindcss.com"></script>
+{{showFile "templates/section/head.tmpl"}}
     <style>
         :root {
             --bg-main: #0b0d12;
@@ -310,7 +303,7 @@
             }
         }
     </style>
-</head>
+
 <body>
     <div class="note-shell">
         <div class="topbar">

+ 9 - 0
cmds/webservice/bin/templates/section/head.tmpl

@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<html lang="ro">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <link rel="icon" type="image/webp" href="/favicon.webp">
+  <title>MyNotes</title>
+  <script src="https://cdn.tailwindcss.com"></script>
+</head>

+ 0 - 10
cmds/webservice/types/types.go

@@ -7,13 +7,3 @@ type Notita struct {
 	Path     string
 	HTML     string `json:"-"`
 }
-type Folder struct {
-	Nume       string
-	Fisiere    []Fisier
-	Subfoldere []Folder
-}
-
-type Fisier struct {
-	Nume string
-	Path string
-}

+ 50 - 0
lib/inout/parser_funcs.go

@@ -0,0 +1,50 @@
+package inout
+
+import (
+	"bytes"
+	"fmt"
+	"net/http"
+	"os"
+	"text/template"
+)
+
+func getFuncMap() template.FuncMap {
+	funcMap := template.FuncMap{
+		"showFile":     showFile,
+		"genSeriesInt": genSeriesInt,
+	}
+	return funcMap
+}
+
+func genSeriesInt(start, stop int64) []int64 {
+	values := make([]int64, 0)
+	for i := start; i <= stop; i++ {
+		values = append(values, i)
+	}
+	return values
+}
+
+func showFile(tmpl string) string {
+	data, err := os.ReadFile(tmpl)
+	if err != nil {
+		return fmt.Sprintf("%+v", err)
+	}
+	return string(data)
+}
+
+func ParseTemplate(file string, input any) ([]byte, int) {
+	var buff bytes.Buffer
+	b, err := os.ReadFile(file)
+	if err != nil {
+		return fmt.Appendf(nil, "%+v", err), http.StatusInternalServerError
+	}
+	tmpl, err := template.New("parse").Funcs(getFuncMap()).Parse(string(b))
+	if err != nil {
+		return fmt.Appendf(nil, "%+v", err), http.StatusInternalServerError
+	}
+	err = tmpl.Execute(&buff, input)
+	if err != nil {
+		return fmt.Appendf(nil, "%+v", err), http.StatusInternalServerError
+	}
+	return buff.Bytes(), http.StatusOK
+}

+ 57 - 0
lib/inout/path.go

@@ -0,0 +1,57 @@
+package inout
+
+import (
+	"fmt"
+	"os"
+	"path/filepath"
+	"strings"
+)
+
+type Folder struct {
+	Nume       string
+	Fisiere    []File
+	Subfoldere []Folder
+}
+
+type File struct {
+	Nume string
+	Path string
+}
+
+func SafeDir(path string) error {
+	path = filepath.Clean(path)
+	if strings.HasPrefix(path, "..") || filepath.IsAbs(path) {
+		return fmt.Errorf("Invalid Path")
+	}
+	return nil
+}
+
+func GetFolderStructure(path string, f *Folder) error {
+	entries, err := os.ReadDir(path)
+	if err != nil {
+		return err
+	}
+	if filepath.Clean(path) != "notes_folder" {
+		f.Nume = filepath.Base(path)
+	} else {
+		f.Nume = "notes_folder"
+	}
+	for _, entry := range entries {
+
+		if entry.IsDir() {
+			sub := Folder{}
+			err = GetFolderStructure(filepath.Join(path, entry.Name()), &sub)
+			if err != nil {
+				return err
+			}
+			f.Subfoldere = append(f.Subfoldere, sub)
+		} else {
+			fisier := File{
+				Nume: entry.Name(),
+				Path: filepath.Join(path, entry.Name()),
+			}
+			f.Fisiere = append(f.Fisiere, fisier)
+		}
+	}
+	return nil
+}

+ 43 - 107
lib/server/handlers.go

@@ -38,7 +38,7 @@ func Wildcard(w http.ResponseWriter, r *http.Request) {
 
 }
 
-func API(w http.ResponseWriter, r *http.Request) {
+func API(w http.ResponseWriter, r *http.Request, s *Server) {
 	action := strings.TrimPrefix(r.URL.Path, "/api/")
 	if r.Method == "POST" {
 		//w.WriteHeader(http.StatusNotImplemented)
@@ -53,18 +53,22 @@ func API(w http.ResponseWriter, r *http.Request) {
 			if n.Folder == "" {
 				n.Folder = "default"
 			}
-			err := safeDirectory(n.Folder)
+			err := inout.SafeDir(n.Folder)
 			if err != nil {
-				w.WriteHeader(http.StatusBadRequest)
-				fmt.Fprintf(w, "Error : %+v, %s", err, n.Folder)
+				resp, code := inout.ParseTemplate("templates/error.tmpl", err)
+				w.Header().Set("Content-Type", "text/html")
+				w.WriteHeader(code)
+				w.Write(resp)
 				return
 			}
-			path := filepath.Join("notes_folder", n.Folder)
+			path := filepath.Join(s.NotesDir, n.Folder)
 			err = os.MkdirAll(path, 0755)
 			fmt.Println(n.Folder)
 			if err != nil {
-				w.WriteHeader(http.StatusBadRequest)
-				fmt.Fprintf(w, "ParseForm error: %+v , %s", err, n.Folder)
+				resp, code := inout.ParseTemplate("templates/error.tmpl", err)
+				w.Header().Set("Content-Type", "text/html")
+				w.WriteHeader(code)
+				w.Write(resp)
 				return
 			}
 
@@ -73,10 +77,12 @@ func API(w http.ResponseWriter, r *http.Request) {
 			//fmt.Println(fisier, r.Form)
 			//return
 
-			err = inout.ObjToFile(filepath.Join("notes_folder", n.Folder, fisier), n, true)
+			err = inout.ObjToFile(filepath.Join(s.NotesDir, n.Folder, fisier), n, true)
 			if err != nil {
-				w.WriteHeader(http.StatusInternalServerError)
-				fmt.Fprintf(w, "%+v", err)
+				resp, code := inout.ParseTemplate("templates/error.tmpl", err)
+				w.Header().Set("Content-Type", "text/html")
+				w.WriteHeader(code)
+				w.Write(resp)
 				return
 			}
 			referinta := r.Referer()
@@ -109,8 +115,10 @@ func API(w http.ResponseWriter, r *http.Request) {
 
 		}
 	}
-	w.WriteHeader(http.StatusMethodNotAllowed)
-	template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, "metoda nepermisa")
+	resp, code := inout.ParseTemplate("templates/error.tmpl", fmt.Errorf("method %s not allowed", r.Method))
+	w.Header().Set("Content-Type", "text/html")
+	w.WriteHeader(code)
+	w.Write(resp)
 }
 
 func Notes(w http.ResponseWriter, r *http.Request, fisier string) {
@@ -130,121 +138,49 @@ func Notes(w http.ResponseWriter, r *http.Request, fisier string) {
 		return
 	}
 	notita.HTML = buf.String()
-	tmpl := template.New("notita")
-	_, err = tmpl.ParseFiles("./templates/notita.tmpl")
-	if err != nil {
-		w.WriteHeader(http.StatusInternalServerError)
-		w.Write([]byte(WEB_ERR))
-		template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
-		return
-	}
-	err = tmpl.ExecuteTemplate(w, "notita.tmpl", notita)
-	if err != nil {
-		w.WriteHeader(http.StatusInternalServerError)
-		w.Write([]byte(WEB_ERR))
-		template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
-		return
-	}
+	resp, code := inout.ParseTemplate("templates/notita.tmpl", notita)
+	w.WriteHeader(code)
+	w.Write(resp)
 }
 
-func safeDirectory(path string) error {
-	path = filepath.Clean(path)
-	if strings.HasPrefix(path, "..") || filepath.IsAbs(path) {
-		return fmt.Errorf("Invalid Path")
-	}
-	return nil
-}
-
-func ListNotes(w http.ResponseWriter, r *http.Request) {
+func ListNotes(w http.ResponseWriter, r *http.Request, s *Server) {
 
 	if r.Method == "GET" {
-		f := types.Folder{}
-		err := buildFolderStructure("./notes_folder", &f)
-		if err != nil {
-			fmt.Println("EROARE la buildFolderStructure:", err)
-			w.WriteHeader(http.StatusBadRequest)
-			template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
-			return
-		}
-		tmpl := template.New("list_notes_test")
-		_, err = tmpl.ParseFiles("./templates/list_notes.tmpl")
-		if err != nil {
-			fmt.Println("EROARE la buildFolderStructure:", err)
-			w.WriteHeader(http.StatusBadRequest)
-			template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
-			return
-		}
-		err = tmpl.ExecuteTemplate(w, "list_notes.tmpl", f)
+		f := inout.Folder{}
+		err := inout.GetFolderStructure(s.NotesDir, &f)
 		if err != nil {
-			fmt.Println("EROARE la buildFolderStructure:", err)
-			w.WriteHeader(http.StatusBadRequest)
-			template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
+			resp, code := inout.ParseTemplate("templates/error.tmpl", err)
+			w.Header().Set("Content-Type", "text/html")
+			w.WriteHeader(code)
+			w.Write(resp)
 			return
 		}
+		resp, code := inout.ParseTemplate("templates/list_notes.tmpl", f)
+		w.Header().Set("Content-Type", "text/html")
+		w.WriteHeader(code)
+		w.Write(resp)
 		return
 	}
 	w.WriteHeader(http.StatusMethodNotAllowed)
 	w.Write([]byte("methoda nepermisa"))
 }
 
-func buildFolderStructure(path string, f *types.Folder) error {
-	entries, err := os.ReadDir(path)
-	if err != nil {
-		return err
-	}
-	if filepath.Clean(path) != "notes_folder" {
-		f.Nume = filepath.Base(path)
-	} else {
-		f.Nume = "notes_folder"
-	}
-	for _, entry := range entries {
-
-		if entry.IsDir() {
-			sub := types.Folder{}
-			err = buildFolderStructure(filepath.Join(path, entry.Name()), &sub)
-			if err != nil {
-				return err
-			}
-			f.Subfoldere = append(f.Subfoldere, sub)
-		} else {
-			fisier := types.Fisier{
-				Nume: entry.Name(),
-				Path: filepath.Join(path, entry.Name()),
-			}
-			f.Fisiere = append(f.Fisiere, fisier)
-		}
-	}
-	return nil
-}
-
 func EditNotes(w http.ResponseWriter, r *http.Request, filename string) {
 
 	if r.Method == "GET" {
 		f := types.Notita{}
 		err := inout.FileToObj(filename, &f)
 		if err != nil {
-			w.WriteHeader(http.StatusBadRequest)
-			template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
-			return
-		}
-		tmpl := template.New("editare")
-		_, err = tmpl.ParseFiles("./templates/edit_notes.tmpl")
-
-		if err != nil {
-			fmt.Println("EROARE la buildFolderStructure:", err)
-			w.WriteHeader(http.StatusBadRequest)
-			template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
-			return
-		}
-		err = tmpl.ExecuteTemplate(w, "edit_notes.tmpl", f)
-		if err != nil {
-			fmt.Println("EROARE la buildFolderStructure:", err)
-			w.WriteHeader(http.StatusBadRequest)
-			template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, err)
-			return
+			resp, code := inout.ParseTemplate("templates/error.tmpl", err)
+			w.WriteHeader(code)
+			w.Write(resp)
 		}
+		resp, code := inout.ParseTemplate("templates/edit_notes.tmpl", f)
+		w.WriteHeader(code)
+		w.Write(resp)
 		return
 	}
-	w.WriteHeader(http.StatusMethodNotAllowed)
-	template.Must(template.ParseFiles("templates/error.tmpl")).Execute(w, "metoda nepermisa")
+	resp, code := inout.ParseTemplate("templates/error.tmpl", fmt.Errorf("method %s not allowed", r.Method))
+	w.WriteHeader(code)
+	w.Write(resp)
 }

+ 2 - 2
lib/server/srv.go

@@ -23,14 +23,14 @@ func (s *Server) Run() {
 	// adding endpoints to the server
 	http.HandleFunc("/", Wildcard)
 	http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
-		API(w, r)
+		API(w, r, s)
 	})
 	http.HandleFunc("/notes/", func(w http.ResponseWriter, r *http.Request) {
 		note := r.URL.Query().Get("note")
 		Notes(w, r, note)
 	})
 	http.HandleFunc("/list_notes/", func(w http.ResponseWriter, r *http.Request) {
-		ListNotes(w, r)
+		ListNotes(w, r, s)
 
 	})
 	http.HandleFunc("/edit/", func(w http.ResponseWriter, r *http.Request) {

+ 4 - 3
lib/server/types.go

@@ -1,7 +1,8 @@
 package server
 
 type Server struct {
-	Host string `json:"srvhost"`
-	Port string `json:"srvport"`
-	Err  error
+	Host     string `json:"srvhost"`
+	Port     string `json:"srvport"`
+	NotesDir string `json:"notes_directory"`
+	Err      error
 }