forked from ichiranakita/etcdkeeper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.go
More file actions
60 lines (53 loc) · 1.33 KB
/
httpserver.go
File metadata and controls
60 lines (53 loc) · 1.33 KB
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
package main
import(
"io"
"log"
"net/http"
"os"
"io/ioutil"
"strings"
"time"
"flag"
"strconv"
)
func main() {
host := flag.String("h","0.0.0.0","host name or ip address")
port := flag.Int("p", 8080, "port")
name := flag.String("n", "/request", "request root name")
flag.CommandLine.Parse(os.Args[1:])
http.HandleFunc(*name, request)
wd, err := os.Getwd()
if err != nil{
log.Fatal(err)
}
http.Handle("/etcdkeeper/", http.FileServer(http.Dir(wd))) // view static directory
err = http.ListenAndServe(*host + ":" + strconv.Itoa(*port), nil)
if err != nil {
log.Fatal(err)
}
}
func request(w http.ResponseWriter, r *http.Request){
if err := r.ParseForm(); err != nil {
log.Println(err.Error())
}
log.Println(r.FormValue("url"), r.Method, r.PostForm.Encode())
body := strings.NewReader(r.PostForm.Encode())
req, err := http.NewRequest(r.Method, r.Form.Get("url"), body)
if err != nil {
io.WriteString(w, err.Error())
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{Timeout: 10*time.Second} // important!!!
resp, err := client.Do(req)
if err != nil {
io.WriteString(w, err.Error())
}else {
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
io.WriteString(w, "Get data failed: " + err.Error())
}else {
io.WriteString(w, string(result))
}
}
}