本文主要是介绍go语言实现简单ngnix样例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
1、代码实现样例:
2、postman调用ngnix,转发:
1、代码实现样例:
package mainimport ("bytes""encoding/json""io""log""net/http""net/http/httputil""net/url"
)func main() {// 定义反向代理的目标服务器地址targetURL, err := url.Parse("http://localhost:8082")if err != nil {log.Fatalf("Failed to parse target URL: %v", err)}// 创建反向代理proxy := httputil.NewSingleHostReverseProxy(targetURL)// 修改请求处理函数http.HandleFunc("/login", handler(proxy))if err := http.ListenAndServe(":8887", nil); err != nil {log.Fatalf("Failed to start proxy server: %v", err)}
}func handler(proxy *httputil.ReverseProxy) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {log.Printf("Received request: %s %s", r.Method, r.URL.Path)// 构造传入参数params := map[string]string{"username": "user1","password": "password1",}jsonData, err := json.Marshal(params)if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)log.Printf("Failed to marshal JSON: %v", err)return}// 发送 POST 请求到目标服务器resp, err := http.Post("http://localhost:8082/login", "application/json", bytes.NewBuffer(jsonData))if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)log.Printf("Failed to send POST request: %v", err)return}defer resp.Body.Close()// 复制响应头部for key, values := range resp.Header {for _, value := range values {w.Header().Add(key, value)}}// 将目标服务器的响应内容直接返回给客户端w.WriteHeader(resp.StatusCode)if _, err := io.Copy(w, resp.Body); err != nil {log.Printf("Failed to write response: %v", err)}log.Printf("Forwarded response: %d", resp.StatusCode)}
}
2、postman调用ngnix,转发:
这篇关于go语言实现简单ngnix样例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!