How to register a new HTTP handler to an HTTP proxy

153 views
Skip to first unread message

Van Fury

unread,
Sep 1, 2023, 3:58:01 AM9/1/23
to golang-nuts
Hi,

I have a working proxy and would like to add register additional handler that will receive HTTP request from an HTTP client and return response. How can register this new handler(FooHandler) to the proxy?

func main() {

    logger.Log.Infof("Server Name: [%s]", description)  

    done := make(chan bool, 1)
    quit := make(chan os.Signal, 1)

    go func() {
        signal.Notify(
            quit,
            syscall.SIGTERM,
            syscall.SIGINT,
        )
    }()

    server := NewServer("127.0.0.10:8085")
   
    go gracefullShutdown(server, quit, done)

    // proxy handler
    http.HandleFunc("/", ProxyProcess)

    // Get tls files
    certFile, keyFile := util.Config.GetCertKeyFiles()

    go func() {
        err := server.ListenAndServeTLS(certFile, keyFile)
        if err != nil && err != http.ErrServerClosed {
            logger.Log.Error(err)
            os.Exit(1)
        }
    }()
    <-done

    logger.Log.Info("Shutting down server ...")
    logger.Log.Info("Server shutdown!")
    os.Exit(0)
}

// NewServer - Create a new server
func NewServer(listening_addr string) *http.Server {

    return &http.Server{
        Addr:      listening_addr,
        TLSConfig: TLSConfig(), // tls confid ommitted
        //Handler:           Router,
        ReadTimeout:       readTimeout * time.Second,
        WriteTimeout:      writeTimeout * time.Second,
        IdleTimeout:       idleTimeout * time.Second,
        ReadHeaderTimeout: readHeaderTimeout * time.Second,
    }
}

Proxy handler function:

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

    remoteUri := "http://127.0.0.5:20015"
    url, err := url.Parse(remoteUri)
    if err != nil {
        logger.Log.Error("Error parsing url:", err)
        return
    }

    //create new proxy
    proxy := CustomNewSingleHostReverseProxy(url)

    // other code omitted

    proxy.ServeHTTPS(res, req)
}

func (p *ReverseProxy) ServeHTTPS(rw http.ResponseWriter, req *http.Request) {

// code ommitted
.....

}

I tried to create a router and updated the Newserver function. With this changes as below request to FooHandler works but proxy request does not work. How can I modify the server to handle both handler requests?

func FooHandler(w http.ResponseWriter, r *http.Request) {
   
    if r.Method == http.MethodPost {
        return
    }
   
    // do some stuff and respond back to http client

    w.Write([]byte("foo"))
}

// route defined for new handler
var routes = Routes{
    Route{
        "FooHandler",
        strings.ToUpper("Post"),
         "/api/v1/foo",
        FooHandler,
    },
}


type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

var Router = NewRouter()

type Routes []Route

func NewRouter() *mux.Router {

    router := mux.NewRouter().StrictSlash(true)

    for _, route := range routes {

        var handler http.Handler

        handler = route.HandlerFunc
        handler = common.RecoverHandler(handler)

        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(handler)
    }
    return router
}

// NewServer updated with router
func NewServer(listening_addr string) *http.Server {

    return &http.Server{
        Addr:      listening_addr,
        TLSConfig: TLSConfig(), // tls confid ommitted
        Handler:           Router,
        ReadTimeout:       readTimeout * time.Second,
        WriteTimeout:      writeTimeout * time.Second,
        IdleTimeout:       idleTimeout * time.Second,
        ReadHeaderTimeout: readHeaderTimeout * time.Second,
    }
}


Reply all
Reply to author
Forward
0 new messages