I am trying to make a simple server with Go language, Why is it not loading the page but keeps showing the ERR message?

huangapple go评论95阅读模式
英文:

I am trying to make a simple server with Go language, Why is it not loading the page but keeps showing the ERR message?

问题

我正在遵循一个教程,我已经逐字核对了所有内容,但似乎仍然无法正常工作。


import (
	"fmt"
	"log"
	"net/http"
)

func formHandler(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		fmt.Fprintf(w, "ParseForm() 错误: %v", err)
		return
	}
	fmt.Fprintf(w, "POST 请求成功")
	name := r.FormValue("name")
	address := r.FormValue("address")
	fmt.Fprintf(w, "姓名 = %s\n", name)
	fmt.Fprintf(w, "地址 = %s\n", address)

}
func helloHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/hello" {
		http.Error(w, "404 页面未找到", http.StatusNotFound)
		return
	}
	if r.Method != "Get" {
		http.Error(w, "不支持的请求方法", http.StatusNotFound)
		return
	}
	fmt.Fprintf(w, "你好!")
}
func main() {
	fileServer := http.FileServer(http.Dir("./static"))
	http.Handle("/", fileServer)
	http.HandleFunc("/form", formHandler)
	http.HandleFunc("/hello", helloHandler)

	fmt.Printf("在端口 8080 启动服务器\n")

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

这是所有页面的错误消息

英文:

I am following a tutorial and I have literally crosschecked everything, It seems not to be working still ....................................................................

>


import (
   "fmt"
   "log"
   "net/http"
)

func formHandler(w http.ResponseWriter, r *http.Request) {
   if err := r.ParseForm(); err != nil {
   	fmt.Fprintf(w, "ParseForm() err: %v", err)
   	return
   }
   fmt.Fprintf(w, "POST request succesfull")
   name := r.FormValue("name")
   address := r.FormValue("address")
   fmt.Fprintf(w, "Name = %s\n", name)
   fmt.Fprintf(w, "Address = %s\n", address)

}
func helloHandler(w http.ResponseWriter, r *http.Request) {
   if r.URL.Path != "/hello" {
   	http.Error(w, "404 not found", http.StatusNotFound)
   	return
   }
   if r.Method != "Get" {
   	http.Error(w, "method is not supported", http.StatusNotFound)
   	return
   }
   fmt.Fprintf(w, "hello!")
}
func main() {
   fileServer := http.FileServer(http.Dir("./static"))
   http.Handle("/", fileServer)
   http.HandleFunc("/form", formHandler)
   http.HandleFunc("/hello", helloHandler)

   fmt.Printf("Starting server at port 8080\n")

   if err := http.ListenAndServe(":8080", nil); err != nil {
   	log.Fatal(err)
   }
}

Here is the Error message for all pages

答案1

得分: 1

我在你的代码中只看到一个问题,它在/hello处理程序中。你使用r.Method != "Get"来检查是否为GET请求,但是HTTP方法是大写的,所以你应该使用r.Method != "GET",或者更好的是使用给定的常量r.Method != http.MethodGet。这样就解决了/hello的问题:

$ curl localhost:8080/hello
hello!

现在,/form处理程序的问题不在你的代码中,但是你试图加载form.html而不是调用form,如果你的项目的static子文件夹中有一个名为form.html的文件,这样可以工作,就像这样(这是一个非常简单的示例):

<!DOCTYPE html>
<html>
  <title>Form</title>
  <body>

    <form method="post" action="/form">
      <label for="name">Name: </label>
      <input type="text" id="name" name="name" />
      <label for="address">Address: </label>
      <input type="text" id="address" name="address" />
      <input type="submit" />
    </form>
  </body>
</html>

这样可以工作,因为你已经在http.Handle("/", fileServer)中处理了静态文件。我不知道你正在遵循的教程,但看起来这就是意图。

另一个尝试直接使用form而不是HTML的选项可以使用类似curl的工具:

$ curl -d 'name=My+Name&address=My+Address' localhost:8080/form
POST request success
Name = My Name
Address = My Address

还有其他工具。HTML的方法对于训练来说应该是可以的。

英文:

I see only one issue in your code, but it is in the /hello handler. You are checking if it is a GET using r.Method != &quot;Get&quot;, but HTTP methods are in uppercase, so you should use r.Method != &quot;GET&quot;, or even better, use the given constant r.Method != http.MethodGet. That solves the /hello issue for me:

$ curl localhost:8080/hello
hello!

Now, the /form handle issue is not in your code, but happens that you are trying to load form.html instead of calling form, which can work if you have a file called form.html in the static subfolder in your project, like this (which is a very minimalist example):

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;title&gt;Form&lt;/title&gt;
  &lt;body&gt;

    &lt;form method=&quot;post&quot; action=&quot;/form&quot;&gt;
      &lt;label for=&quot;name&quot;&gt;Name: &lt;/label&gt;
      &lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; /&gt;
      &lt;label for=&quot;address&quot;&gt;Address: &lt;/label&gt;
      &lt;input type=&quot;text&quot; id=&quot;address&quot; name=&quot;address&quot; /&gt;
      &lt;input type=&quot;submit&quot; /&gt;
    &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;

That works because you are already handling static files in http.Handle(&quot;/&quot;, fileServer). I don't know the tutorial you are following, but looks like that was the intention.

Another option to try form directly, without HTML could be using something like curl:

$ curl -d &#39;name=My+Name&amp;address=My+Address&#39; localhost:8080/form
POST request succesfullName = My Name
Address = My Address

There are other tools. The HTML one should be fine for training.

答案2

得分: 0

我可以看到在你的helloHandler函数中还有一个错误,当你比较请求的方法时,你应该将其与"GET"而不是"Get"进行比较。

更多信息请参考:https://pkg.go.dev/net/http#pkg-constants

我在本地运行了这段代码,对我来说在本地运行得很好。你能否提供你所遇到的确切错误?

英文:

I can see there is one more error in your helloHandler function when you compare the request Method, you should compare it with "GET" and not "Get".

For more info look at: https://pkg.go.dev/net/http#pkg-constants

I ran this code locally it is working fine locally for me. With this Method change I mentioned above. Can you post the exact error you are getting?

huangapple
  • 本文由 发表于 2022年7月8日 15:05:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/72907825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定