-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathginproxy.go
More file actions
43 lines (38 loc) · 962 Bytes
/
Copy pathginproxy.go
File metadata and controls
43 lines (38 loc) · 962 Bytes
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
package ginproxy
import (
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"strings"
)
type ProxyOptions struct {
Target string
PathRewrite string
}
func HandleProxy(path string, proxyOption ProxyOptions) gin.HandlerFunc {
return func(ctx *gin.Context) {
if strings.Index(ctx.Request.RequestURI, path) == 0 {
client := &http.Client{}
requestUrl := strings.Replace(ctx.Request.RequestURI, proxyOption.PathRewrite, "", -1)
url := proxyOption.Target + requestUrl
req, err := http.NewRequest(ctx.Request.Method, url, ctx.Request.Body)
if err != nil {
println(err)
return
}
req.Header = ctx.Request.Header
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
for key, value := range resp.Header {
if len(value) == 1 {
ctx.Writer.Header().Add(key, value[0])
}
}
ctx.Status(resp.StatusCode)
ctx.Writer.Write(body)
} else {
ctx.Next()
}
}
}