一直在开发一个小型 Web 应用程序,想尝试使用 nginx 和 Golang 作为后端。这是我的第一个 Golang Web 项目,因此对 Golang 还很陌生。无论如何,我的 HTML 登录页面的反向代理存在问题:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="loginStyle.css">
<title>Cosmic Cloud Login</title>
</head>
<body>
<div class="loginContainer">
<h1 class="headerText">Login</h1>
<p>Please enter your login information</p>
<form action="/login" method="POST">
<div class="inputGroup">
<label for="Username">Username</label>
<input type="Username" id="Username" name="Username" placeholder="Enter your username" required>
</div>
<div class="inputGroup">
<label for="Password">Password</label>
<input type="Password" id="Password" name="Password" placeholder="Enter your password" required>
</div>
<button type="submit" class="loginButton">Login</button>
</form>
</div>
</body>
</html>
nginx.conf文件如下:
server {
listen 80;
location / {
root /var/www/html;
index index.html;
}
location /login {
proxy_pass http://0.0.0.0:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Go文件如下:
package main
import (
"fmt"
"net/http"
)
var validUsername = "test"
var validPassword = "test1234"
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid Request method", http.StatusMethodNotAllowed)
return
}
username := r.FormValue("Username")
password := r.FormValue("Password")
if username == validUsername && password == validPassword {
fmt.Fprint(w, "Login Successfull!")
} else {
http.Error(w, "Invalid Username or Password", http.StatusUnauthorized)
}
}
func main() {
http.HandleFunc("/login", loginHandler)
fmt.Println("Server is running on :8080")
http.ListenAndServe(":8080", nil)
}
发送 post 请求时,除非您指定端口 8080,否则 golang 后端永远不会收到它。(例如“http://IP/login”不起作用)(“http://IP:8080/login”起作用)我在本地计算机和网络上的另一台计算机上都尝试过。TLDR:nginx 无法正确将 POST 请求从 nginx Web 服务器(端口 80)发送到 Golang 后端正在监听的端口(端口 8080)。非常感谢您的帮助,谢谢!
编辑:此外,这可能不是防火墙问题,因为我在测试环境中禁用了 ufw。