-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathrego.go
81 lines (66 loc) · 1.68 KB
/
rego.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
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"regexp"
"strconv"
)
type MatchResultResponse struct {
Matches [][]string `json:"matches"`
GroupsName []string `json:"groupsName"`
}
func handler(rw http.ResponseWriter, req *http.Request) {
t, _ := template.ParseFiles("index.html")
t.Execute(rw, nil)
}
func regExpHandler(rw http.ResponseWriter, req *http.Request) {
var matches [][]string
req.ParseForm()
regexpString := req.FormValue("regexp")
testString := req.FormValue("testString")
findAllSubmatch, _ := strconv.ParseBool(req.FormValue("findAllSubmatch"))
log.Printf("Regexp : %s", regexpString)
log.Printf("Test string : %s", testString)
log.Printf("Find all : %t", findAllSubmatch)
m := &MatchResultResponse{}
r, err := regexp.Compile(regexpString)
if err != nil {
log.Printf("Invalid RegExp : %s \n", regexpString)
rw.WriteHeader(500)
fmt.Fprintf(rw, "Invalid RegExp : %s", regexpString)
return
}
if findAllSubmatch {
matches = r.FindAllStringSubmatch(testString, -1)
} else {
matches = [][]string{r.FindStringSubmatch(testString)}
}
log.Println(matches)
if len(matches) > 0 {
m.Matches = matches
m.GroupsName = r.SubexpNames()[1:]
}
enc := json.NewEncoder(rw)
enc.Encode(m)
}
func main() {
// Main handler (index.html)
http.HandleFunc("/", handler)
// Regex testing service
http.HandleFunc("/test_regexp/", regExpHandler)
// Static file serving
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
// Launch server
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Fatal(err)
}
}