]> Sergey Matveev's repositories - godlighty.git/blob - rc/example.cfg/proxied-host.go
Safer query passing
[godlighty.git] / rc / example.cfg / proxied-host.go
1 // Reverse proxy
2
3 package cfg
4
5 import (
6         "fmt"
7         "io"
8         "net/http"
9         "net/url"
10
11         "go.stargrave.org/godlighty"
12 )
13
14 func init() {
15         host := "some-proxied-host.com"
16         godlighty.Hosts[host] = &godlighty.HostCfg{
17                 Hooks: []godlighty.Hook{
18                         func(w http.ResponseWriter, r *http.Request) bool {
19                                 var err error
20                                 if r.URL, err = url.ParseRequestURI(r.RequestURI); err != nil {
21                                         panic(err)
22                                 }
23                                 r.URL.Scheme = "http"
24                                 r.URL.Host = "[dead::beaf]"
25                                 r.RequestURI = ""
26                                 resp, err := http.DefaultClient.Do(r)
27                                 if err != nil {
28                                         fmt.Printf("%s %s \"%s %+q %s\" %d \"%s\" \"%s\"\n",
29                                                 r.RemoteAddr, host, r.Method, godlighty.PathWithQuery(r.URL),
30                                                 r.Proto, http.StatusBadGateway, err.Error(),
31                                                 r.Header.Get("User-Agent"),
32                                         )
33                                         http.Error(w, err.Error(), http.StatusBadGateway)
34                                         return true
35                                 }
36                                 for k, vs := range resp.Header {
37                                         for _, v := range vs {
38                                                 w.Header().Add(k, v)
39                                         }
40                                 }
41                                 w.WriteHeader(resp.StatusCode)
42                                 size, _ := io.Copy(w, resp.Body)
43                                 resp.Body.Close()
44                                 fmt.Printf("%s %s \"%s %+q %s\" %d %d \"%s\"\n",
45                                         r.RemoteAddr, host, r.Method, godlighty.PathWithQuery(r.URL),
46                                         r.Proto, resp.StatusCode, size,
47                                         r.Header.Get("User-Agent"),
48                                 )
49                                 return true
50                         },
51                 },
52         }
53 }