Changeset 96 in code


Ignore:
Timestamp:
Aug 11, 2019, 8:34:33 AM (6 years ago)
Author:
alex
Message:

[mod] follow HTTP redirect (only GET HTTP method)

close #48

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/morty.go

    r95 r96  
    3636
    3737const VERSION = "v0.2.0"
     38
     39const MAX_REDIRECT_COUNT = 5
    3840
    3941var CLIENT *fasthttp.Client = &fasthttp.Client{
     
    288290        }
    289291
    290         parsedURI, err := url.Parse(string(requestURI))
     292        p.ProcessUri(ctx, string(requestURI), 0)
     293}
     294
     295func (p *Proxy) ProcessUri(ctx *fasthttp.RequestCtx, requestURI string, redirectCount int) {
     296        parsedURI, err := url.Parse(requestURI)
    291297
    292298        if err != nil {
     
    339345                        loc := resp.Header.Peek("Location")
    340346                        if loc != nil {
    341                                 rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
    342                                 url, err := rc.ProxifyURI(loc)
    343                                 if err == nil {
    344                                         ctx.SetStatusCode(resp.StatusCode())
    345                                         ctx.Response.Header.Add("Location", url)
    346                                         log.Println("redirect to", string(loc))
     347                                log.Println("redirect to", string(loc))
     348                                if ctx.IsGet() {
     349                                        // GET method: Morty follows the redirect
     350                                        if redirectCount < MAX_REDIRECT_COUNT {
     351                                                p.ProcessUri(ctx, string(loc), redirectCount+1)
     352                                        } else {
     353                                                p.serveMainPage(ctx, 310, errors.New("Too many redirects"))
     354                                        }
    347355                                        return
     356                                } else {
     357                                        // Other HTTP methods: Morty does NOT follow the redirect
     358                                        rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
     359                                        url, err := rc.ProxifyURI(loc)
     360                                        if err == nil {
     361                                                ctx.SetStatusCode(resp.StatusCode())
     362                                                ctx.Response.Header.Add("Location", url)
     363                                                return
     364                                        }
    348365                                }
    349366                        }
Note: See TracChangeset for help on using the changeset viewer.