Ver Fonte

added wildcard endpoint handler

turos.robert há 4 semanas atrás
pai
commit
70897bdedb

+ 1 - 1
cmds/webservice/bin/templates/index.tmpl

@@ -5,7 +5,7 @@
     <title>Site Fain </title>
     </head>
     <body>
-    <form action = "/test" method = "post"><button type = "submit">Apasa-ma</button></form>
+    <form action = "/testul" method = "get"><button type = "submit">Apasa-ma</button></form>
     </body>
 
 </html>

+ 10 - 0
cmds/webservice/bin/templates/testul.tmpl

@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<html lang = "eng">
+    <head>
+    <meta charset = "UTF-8">
+    <title>Site Fain </title>
+    </head>
+      <body>
+    <form action = "/index" method = "get"><button type = "submit">Test Magic</button></form>
+    </body>
+</html>

+ 18 - 4
lib/server/handlers.go

@@ -2,16 +2,30 @@ package server
 
 import (
 	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
 
 	"git.linuxit.ro/turos.robert/mynotes/lib/inout"
 )
 
 func Wildcard(w http.ResponseWriter, r *http.Request) {
-	if r.Method != "GET" {
-		w.Write(inout.FileToBytes("templates/index.tmpl"))
+
+	if r.Method == "GET" {
+		endpoint := strings.TrimPrefix(r.URL.Path, "/")
+		if endpoint == "" {
+			//in cazul in care apelam root
+			endpoint = "index"
+		}
+		path := filepath.Join("templates", endpoint+".tmpl")
+		_, err := os.Stat(path)
+		if err != nil {
+			w.WriteHeader(http.StatusNotFound)
+			w.Write(inout.FileToBytes("templates/error.tmpl"))
+			return
+		}
+		w.Write(inout.FileToBytes(path))
 		return
 	}
-	w.WriteHeader(http.StatusMethodNotAllowed)
-	w.Write(inout.FileToBytes("templates/error.tmpl"))
 
 }

+ 1 - 1
lib/server/srv.go

@@ -28,7 +28,7 @@ func Ceva(s *Server) http.HandlerFunc {
 func (s *Server) Run() {
 	// adding endpoints to the server
 	http.HandleFunc("/", Wildcard)
-	http.Handle("/ceva", Ceva(s))
+	http.Handle("/dada", Ceva(s))
 
 	//running server
 	fmt.Printf("Server running at http://%s:%s/\n", s.Host, s.Port)