当前位置:   article > 正文

go语言实现简单ngnix样例

go语言实现简单ngnix样例

目录

1、代码实现样例:

2、postman调用ngnix,转发:


1、代码实现样例:

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "log"
  7. "net/http"
  8. "net/http/httputil"
  9. "net/url"
  10. )
  11. func main() {
  12. // 定义反向代理的目标服务器地址
  13. targetURL, err := url.Parse("http://localhost:8082")
  14. if err != nil {
  15. log.Fatalf("Failed to parse target URL: %v", err)
  16. }
  17. // 创建反向代理
  18. proxy := httputil.NewSingleHostReverseProxy(targetURL)
  19. // 修改请求处理函数
  20. http.HandleFunc("/login", handler(proxy))
  21. if err := http.ListenAndServe(":8887", nil); err != nil {
  22. log.Fatalf("Failed to start proxy server: %v", err)
  23. }
  24. }
  25. func handler(proxy *httputil.ReverseProxy) http.HandlerFunc {
  26. return func(w http.ResponseWriter, r *http.Request) {
  27. log.Printf("Received request: %s %s", r.Method, r.URL.Path)
  28. // 构造传入参数
  29. params := map[string]string{
  30. "username": "user1",
  31. "password": "password1",
  32. }
  33. jsonData, err := json.Marshal(params)
  34. if err != nil {
  35. http.Error(w, err.Error(), http.StatusInternalServerError)
  36. log.Printf("Failed to marshal JSON: %v", err)
  37. return
  38. }
  39. // 发送 POST 请求到目标服务器
  40. resp, err := http.Post("http://localhost:8082/login", "application/json", bytes.NewBuffer(jsonData))
  41. if err != nil {
  42. http.Error(w, err.Error(), http.StatusInternalServerError)
  43. log.Printf("Failed to send POST request: %v", err)
  44. return
  45. }
  46. defer resp.Body.Close()
  47. // 复制响应头部
  48. for key, values := range resp.Header {
  49. for _, value := range values {
  50. w.Header().Add(key, value)
  51. }
  52. }
  53. // 将目标服务器的响应内容直接返回给客户端
  54. w.WriteHeader(resp.StatusCode)
  55. if _, err := io.Copy(w, resp.Body); err != nil {
  56. log.Printf("Failed to write response: %v", err)
  57. }
  58. log.Printf("Forwarded response: %d", resp.StatusCode)
  59. }
  60. }

2、postman调用ngnix,转发:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/509410
推荐阅读
相关标签
  

闽ICP备14008679号