PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, June 24, 2022

[FIXED] How to handle error using NewSingleHostReverseProxy

 June 24, 2022     go, http, reverse-proxy     No comments   

Issue

I'm trying to do a load balancer to study some go packages.

I want to handle errors when the request timeout or give 404 error but can't find how to do that.

func main() {
    // start server
    http.HandleFunc("/", handleRequestAndRedirect)

    if err := http.ListenAndServe(getListenAddress(), nil); err != nil {
        panic(err)
    }
}

func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {

    ur, _ := url.Parse("https://www.instagram.com/")
    proxy := httputil.NewSingleHostReverseProxy(ur)
    // Update the headers to allow for SSL redirection
    req.URL.Host = ur.Host
    req.URL.Scheme = ur.Scheme
    req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
    req.Host = ur.Host
    req.Header.Set("Key", "Teste")

    proxy.ServeHTTP(res, req)

}


Solution

use proxy.ErrorHandler

ErrorHandler func(http.ResponseWriter, *http.Request, error)

  func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {

        ur, _ := url.Parse("https://www.instagram.com/")
        proxy := httputil.NewSingleHostReverseProxy(ur)
        // Update the headers to allow for SSL redirection
        req.URL.Host = ur.Host
        req.URL.Scheme = ur.Scheme
        req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
        req.Host = ur.Host
        req.Header.Set("Key", "Teste")

        proxy.ErrorHandler = ErrHandle
        proxy.ServeHTTP(res, req)
    }

    func ErrHandle(res http.ResponseWriter, req *http.Request, err error) {
        fmt.Println(err)
    }     


Answered By - dchaofei
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing