forked from pksingh/web-echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (87 loc) · 2.04 KB
/
main.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 (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world!\n")
}
type MsgHandler struct {
Msg string
}
func (mh *MsgHandler) greet(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", mh.Msg)
}
type RequestBody struct {
String string
// Add other items
}
// Request is the same as http.Request minus the bits that break json.Marshall
type Request struct {
Method string
URL *url.URL
Proto string // "HTTP/1.0"
ProtoMajor int // 1
ProtoMinor int // 0
Header http.Header
Body RequestBody
ContentLength int64
TransferEncoding []string
Host string
//Form url.Values
//PostForm url.Values
//MultipartForm *multipart.Form
Trailer http.Header
RemoteAddr string
RequestURI string
//TLS *tls.ConnectionState
}
const megabytes = 1048576
func echo(w http.ResponseWriter, r *http.Request) {
e := Request{}
e.Method = r.Method
e.URL = r.URL
e.Proto = r.Proto
e.ProtoMajor = r.ProtoMajor
e.ProtoMinor = r.ProtoMinor
e.Header = r.Header
e.Body = RequestBody{}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1*megabytes))
if err != nil {
log.Fatal(err)
}
if err := r.Body.Close(); err != nil {
log.Fatal(err)
}
e.Body.String = string(body)
e.ContentLength = r.ContentLength
e.TransferEncoding = r.TransferEncoding
e.Host = r.Host
e.Trailer = r.Trailer
e.RemoteAddr = r.RemoteAddr
e.RequestURI = r.RequestURI
b, err := json.Marshal(e)
if err != nil {
log.Fatal(err)
}
fmt.Fprint(w, string(b))
}
func main() {
port := flag.Int("p", 80, "Port")
msg := flag.String("m", "Message", "-m \"Welcome!\"")
flag.Parse()
mh := &MsgHandler{Msg: *msg}
log.Println(fmt.Sprintf("Listening on port %v...", *port))
http.HandleFunc("/", hello)
http.HandleFunc("/greet", mh.greet)
http.HandleFunc("/echo", echo)
//http.ListenAndServe(":80", nil)
log.Fatal(http.ListenAndServe(
fmt.Sprintf(":%v", *port), nil))
}