summaryrefslogtreecommitdiff
path: root/web_server/web_server.go
blob: 0bf9306918c0e3160caa94665dda21b50a8bccff (plain)
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
package main

import (
	 "fmt"
	 "log"
    "net/http"
	 "strings"
	 "net"
	 "bufio"
	 //"html"
)

func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Expires", "0")

	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	tmp := strings.Split(r.URL.Path, "/");
	fmt.Println(tmp);
	if tmp[1] == "add" && len(tmp[2]) != 0 {
		fmt.Println("Request add:");
		fmt.Println("Sending a request to add: " + tmp[2] + "...");
		conn, err := net.Dial("tcp", "localhost:5555");
		if err != nil {
			log.Fatal(err);
		}
		defer conn.Close();

		fmt.Fprintf(conn, "{\"type\": 1, \"url\": \"%s\"}", tmp[2]);
		res, _ := bufio.NewReader(conn).ReadBytes('\n');
		fmt.Println(string(res));
		
		w.Write(res);

		return;
	}else if len(tmp[1]) == 6 {
		s := tmp[1];
		fmt.Println(tmp[1]);
		conn, err := net.Dial("tcp", "localhost:5555");
		if err != nil {
			log.Fatal(err);
		}
		defer conn.Close();

		fmt.Println(s);
		fmt.Fprintf(conn, "{\"type\": 2, \"url\": \"%s\"}", s);
		res, _ := bufio.NewReader(conn).ReadBytes('\n');
		fmt.Println(string(res));
		http.Redirect(w, r, string(res), http.StatusPermanentRedirect);

	}else{
		//fmt.Fprintf(w, "oi", r.URL.Path[1:]);
	}
}

func add_page(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Expires", "0")
	tmp := strings.Split(r.URL.Path, "/");
	fmt.Println(tmp);
}

func main() {
	/*fmt.Println("Port 5556");
	server := &http.Server{
		Addr: "localhost:5556",
		Handler: http.HandlerFunc(handler),
	};
	server.SetKeepAlivesEnabled(false);*/

	mux := http.NewServeMux();
	mux.HandleFunc("/", handler);
	//mux.HandleFunc("/add", add_page);
	server := &http.Server{
		Addr: "localhost:5556",
		Handler: mux,
	};
	server.SetKeepAlivesEnabled(false);
	fmt.Println("Listen on port 5556");
	
	//http.HandleFunc("/", handler);
	log.Fatal(server.ListenAndServe());
}