相关文档

ReverseProxy

样例代码

package main

import (
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
)

func NewReverseProxy(target *url.URL) *httputil.ReverseProxy {
    director := func(req *http.Request) {
        req.URL.Scheme = target.Scheme
        req.URL.Host = target.Host

        log.Printf("req %+v \n", req)
    }
    modifyresponse := func(response *http.Response) error {
        response.Header.Set("Access-Control-Allow-Origin", "*")
        response.Header.Set("Access-Control-Allow-Methods", "*")
        response.Header.Set("Access-Control-Allow-Headers", "*")

        log.Printf("res %+v \n", response)
        return nil
    }
    return &httputil.ReverseProxy{
        Director:       director,
        ModifyResponse: modifyresponse,
    }
}

func main() {
    addr := ":8080"

    proxy := NewReverseProxy(&url.URL{
        Scheme: "http",
        Host:   "target.com",
    })

    log.Printf("listen at [%s]\n", addr)
    log.Fatal(http.ListenAndServe(addr, proxy))
}
Last modification:February 27, 2022
If you think my article is useful to you, please feel free to appreciate