-
Notifications
You must be signed in to change notification settings - Fork 0
/
poster.go
99 lines (86 loc) · 1.66 KB
/
poster.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
)
type method string
// http methods
const (
post method = "POST"
put method = "PUT"
delete method = "DELETE"
)
type query struct {
m method
url string
body string
}
var client = &http.Client{}
func via(m string) method {
switch m {
case "post":
return post
case "put":
return put
case "delete":
return delete
}
return post
}
func extract(uri string) (query, error) {
colon := strings.Index(uri, ":")
if colon == -1 {
return query{}, errors.New("skip")
}
slash := strings.Index(uri[1:], "/") + 1
question := strings.Index(uri, "?")
var schema string
if uri[slash+1:colon] == "http" {
schema = "http://"
} else {
schema = "https://"
}
body, _ := url.QueryUnescape(uri[question+1:])
return query{m: via(uri[1:slash]), url: schema + uri[colon+1:question], body: body}, nil
}
func handle(w http.ResponseWriter, r *http.Request) {
q, err := extract(r.RequestURI)
if err != nil {
return
}
req, err := http.NewRequest(string(q.m), q.url, strings.NewReader(q.body))
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json;charset=UTF-8")
req.Header.Add("User-Agent", "insomnia/2020.3.3")
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
w.Write(body)
}
func main() {
http.HandleFunc("/", handle)
port := "1230"
if len(os.Args) >= 2 {
port = os.Args[1]
}
err := http.ListenAndServe("0.0.0.0:"+port, nil)
if err != nil {
fmt.Println("cannot start server")
}
}