Skip to content

Instantly share code, notes, and snippets.

@slawosz
Last active December 26, 2015 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slawosz/7141170 to your computer and use it in GitHub Desktop.
Save slawosz/7141170 to your computer and use it in GitHub Desktop.
Various go research scripts: * reading http request
package main
import (
"net/http"
"bytes"
"bufio"
"net/http/httputil"
"fmt"
"log"
)
type HttpInput struct {
data chan *bytes.Buffer
port string
proxyHandler *httputil.ReverseProxy
}
func NewHttpInput(port string) (input *HttpInput) {
input = &HttpInput{port: port}
input.data = make(chan *bytes.Buffer)
input.proxyHandler = &httputil.ReverseProxy{
Director: func(req *http.Request) {
// dump request
buffer := &bytes.Buffer{}
req.Write(buffer)
input.data <- buffer
fmt.Println("Forwarding request")
// this line gives me problems, why?
//req, _ = http.ReadRequest(bufio.NewReader(buffer))
// why I need to add it?
req.URL.Scheme = "http"
req.URL.Host = "localhost:8081"
},
}
go input.Serve()
return
}
func (input HttpInput) Serve() {
for {
buffer := <-input.data
fmt.Println("Got data")
req,_ := http.ReadRequest(bufio.NewReader(buffer))
req.URL.Scheme = "http"
req.URL.Host = "localhost:8082"
req.RequestURI = ""
go func() {
resp, err := http.DefaultClient.Do(req)
}()
}
}
func main() {
log.SetFlags(log.Lshortfile)
input := NewHttpInput("8888")
log.Fatal(http.ListenAndServe(":8080", input.proxyHandler))
}
// prints incoming request to stdout
// curl --data "param1=value1&param2=value2" localhost:8080/bar
package main
import (
"bytes"
"net/http"
"fmt"
"log"
)
func main() {
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
buffer := &bytes.Buffer{}
r.Write(buffer)
fmt.Println(buffer.String())
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment