-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiki.go
125 lines (112 loc) · 3.83 KB
/
wiki.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"errors"
"html/template"
"log"
"net/http"
"os"
"regexp"
)
var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
var templates = template.Must(template.ParseFiles("edit.html", "view.html"))
func main() {
file_error := writeErrorsFile("Error.txt") // Abre el archivo Error.txt
defer file_error.Close() // Cierra el archivo Error.txt al finalizar la ejecución del programa
log.SetOutput(file_error) // Escribe los logs en el archivo Error.txt
// http.HandleFunc("/", handler) // Le dice a http que maneje todas las requests a / con handler
http.HandleFunc("/view/", makeHandler(viewHandler))
http.HandleFunc("/edit/", makeHandler(editHandler))
http.HandleFunc("/save/", makeHandler(saveHandler))
// Uso select case segun el path que se coloque en el navegador
// En caso que haya un error, se anota el error
log.Fatal(http.ListenAndServe(":8080", nil))
}
func getTitle(w http.ResponseWriter, r *http.Request) (string, error) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return "", errors.New("invalid Page Title")
}
return m[2], nil // The title is the second subexpression.
}
type Page struct {
Title string
Body []byte
}
func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
fn(w, r, m[2])
}
}
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
body := r.FormValue("body")
p := &Page{Title: title, Body: []byte(body)}
err := p.save()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
}
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
return
}
renderTemplate(w, "view", p)
}
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title}
}
renderTemplate(w, "edit", p)
}
func writeErrorsFile(filename string) *os.File {
// Crea Fila del objeto os.File para escribir logs y err en caso que hayan errores
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) // (nombre del archivo,Agregar contenido|Crear si no existe|Escribir solo, permisos de escritura y lectura para el dueño, grupos y otros usuarios)
if err != nil {
log.Fatal(err)
}
return file
}
/*
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { //Carga el template edit.html y carga los datos de la pagina p
t, err := template.ParseFiles(tmpl + ".html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
*/
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
err := templates.ExecuteTemplate(w, tmpl+".html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
/*func handler(w http.ResponseWriter, r *http.Request) { // w es la respuesta que se le envía al cliente, r es el request que se recibe del cliente y r es la solicitud
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}// Se usa fmt para este*/
func (p *Page) save() error { //Guarda la pagina en un archivo
filename := p.Title + ".txt"
return os.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error) { // Carga la pagina desde un archivo
filename := title + ".txt"
body, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}