Skip to content

Instantly share code, notes, and snippets.

@KyonLi
Created May 22, 2019 07:56
Show Gist options
  • Save KyonLi/6aab8f3a9524a3dc9896a587aebba235 to your computer and use it in GitHub Desktop.
Save KyonLi/6aab8f3a9524a3dc9896a587aebba235 to your computer and use it in GitHub Desktop.
echo server
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
func echo(w http.ResponseWriter, r *http.Request) {
u := r.URL
resp := fmt.Sprintf(`Method: %s
Host: %s
Path: %s
Query: %s
Fragment: %s
Header: %s
Body: %s
ContentLength: %d
TransferEncoding: %s
RemoteAddr: %s`,
r.Method,
r.Host,
u.Path,
func() string {
q, err := url.QueryUnescape(u.RawQuery)
if err != nil {
return u.RawQuery
}
return q
}(),
u.Fragment,
r.Header,
func() string {
buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(r.Body)
b := buf.String()
q, err := url.QueryUnescape(b)
if err != nil {
return b
}
return q
}(),
r.ContentLength,
r.TransferEncoding,
func() string {
ip := r.Header.Get("X-Real-IP")
if ip != "" {
return ip
}
ip = strings.Split(r.Header.Get("X-Forwarded-For"), ", ")[0]
if ip != "" {
return ip
}
return r.RemoteAddr
}(),
)
_, _ = io.WriteString(w, resp)
}
func main() {
http.HandleFunc("/", echo)
fmt.Println(http.ListenAndServe("127.0.0.1:2323", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment