Golang运行main.go时遇到错误怎么办

Golang运行main.go时遇到错误怎么办 在运行我的项目时遇到以下错误: # command-line-arguments runtime.main_main·f: function main is undeclared in the main package

main.go

package main

import (
	"html/template"
	"net/http"
)

type Contact struct {
	Email   string
	Subject string
	Message string
}

func Main() {
	tmpl := template.Must(template.ParseFiles("form.html"))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			tmpl.Execute(w, nil)
			return
		}
		details := Contact{
			Email:   r.FormValue("email"),
			Subject: r.FormValue("subject"),
			Message: r.FormValue("message"),
		}

		_ = details

		tmpl.Execute(w, struct{ succes bool }{true})
	})
	http.ListenAndServe(":8080", nil)

}

form.html

{{if.Success}}
<h1> Thanks we received the message</h1>
{{else}}
<h1> Contact</h1>
<form method="POST">
    <label>Email:</label><br />
    <input type="text" name="email"><br />
    <label>Subject: </label><br />
    <input type="text" name="Subject"><br />
    <label>Message:</label><br />
    <textarea name="message"></textarea>
    <input type="submit">
</form>
{{end}}

更多关于Golang运行main.go时遇到错误怎么办的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

main 函数必须命名为 main(),而不是 Main()

更多关于Golang运行main.go时遇到错误怎么办的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


好的,谢谢

这个错误是因为你的主函数命名不正确。Go语言要求可执行程序的入口函数必须是 main(),而不是 Main()。函数名区分大小写。

修改你的 main.go 文件:

package main

import (
	"html/template"
	"net/http"
)

type Contact struct {
	Email   string
	Subject string
	Message string
}

func main() { // 改为小写的 main
	tmpl := template.Must(template.ParseFiles("form.html"))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			tmpl.Execute(w, nil)
			return
		}
		details := Contact{
			Email:   r.FormValue("email"),
			Subject: r.FormValue("subject"),
			Message: r.FormValue("message"),
		}

		_ = details

		tmpl.Execute(w, struct{ Success bool }{true}) // 修正拼写错误:succes -> Success
	})
	http.ListenAndServe(":8080", nil)
}

同时修正 form.html 模板中的字段名,使其与代码中的结构体字段匹配:

{{if .Success}} <!-- 修正语法:if.Success -> if .Success -->
<h1> Thanks we received the message</h1>
{{else}}
<h1> Contact</h1>
<form method="POST">
    <label>Email:</label><br />
    <input type="text" name="email"><br />
    <label>Subject: </label><br />
    <input type="text" name="subject"><br /> <!-- 改为小写 subject -->
    <label>Message:</label><br />
    <textarea name="message"></textarea>
    <input type="submit">
</form>
{{end}}

主要修改:

  1. func Main()func main()
  2. struct{ succes bool }struct{ Success bool }
  3. 模板中 if.Successif .Success
  4. HTML 表单中 name="Subject"name="subject"(保持与 r.FormValue("subject") 一致)

修改后使用 go run main.go 命令运行程序。

回到顶部