美好的一天!在这个程序中,我为餐厅制作菜单,包括Handle功能。
问题陈述:
我无法将数组Name, Price
与函数getall
和get
连接起来。
package main
import (
"fmt"
"net/http"
"io"
"strconv"
"net/url"
)
type Menu struct {
Name string
Price int
description string
}
func (m Menu) String() string {
return fmt.Sprintf("%s: %s", m.Name, m.Price, )
}
func main() {
x :=[]Menu{
{Name:"Crispy", Price:31},
{Name:"Burger", Price:42},
{Name:"Superstar",Price:17},
/*{"Cola", 26},
{Name:"Superstar", Price:40},
{Name:"Nuggets", Price:19},*/
}
//getall(&x)
fmt.Println(x)
http.HandleFunc("/getall", getall)
http.HandleFunc("/get", get)
http.ListenAndServe(":8080", nil)
}
func getall(w http.ResponseWriter, r *http.Request) {
for _,num := range []Menu{}{
io.WriteString(w, "<p>"+m.Name+" Price "+strconv.Itoa(num)+"</p>")
}
}
func get(w http.ResponseWriter, r *http.Request) {
url := url.URL{}
println(url.String())
attr := r.URL.Query()
fmt.Println(attr)
id := attr["id"][0]
fmt.Println("id of request " + id)
v := id
d:= []Menu{}
if a, err := strconv.Atoi(v);
err == nil {
io.WriteString(w, "<p> "+Name[a-1]+" price "+strconv.Itoa(d[a-1])+"</p>")
}
}
帮助我在getall
和get
函数中实现数组。
答案 0 :(得分:0)
我想帮助你,因为看起来你真的想学习去吧。我对你的代码做了一些改动。我已经移动了每个处理程序中的菜单列表。你可以把它保持全球化。找到下面的更改代码。
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"strconv"
)
type Menu struct {
Name string
Price int
description string
}
func (m Menu) String() string {
return fmt.Sprintf("%s: %s", m.Name, m.Price)
}
func main() {
fmt.Println(x)
http.HandleFunc("/getall", getall)
http.HandleFunc("/get", get)
http.ListenAndServe(":8080", nil)
}
func getall(w http.ResponseWriter, r *http.Request) {
x := []Menu{
{Name: "Crispy", Price: 31},
{Name: "Burger", Price: 42},
{Name: "Superstar", Price: 17},
}
for _, m := range x {
io.WriteString(w, "<p>"+m.Name+" Price "+strconv.Itoa(m.Price)+"</p>")
}
}
func get(w http.ResponseWriter, r *http.Request) {
x := []Menu{
{Name: "Crispy", Price: 31},
{Name: "Burger", Price: 42},
{Name: "Superstar", Price: 17},
}
url := url.URL{}
println(url.String())
attr := r.URL.Query()
fmt.Println(attr)
id := attr["id"][0]
fmt.Println("id of request " + id)
v := id
if a, err := strconv.Atoi(v); err == nil {
io.WriteString(w, "<p> "+x[a-1].Name+" price "+strconv.Itoa(x[a-1].Price)+"</p>")
}
}
尝试访问:http://localhost:8080/getall或http://localhost:8080/get?id=1
答案 1 :(得分:0)
用户for m :=range menu{...}
实现getall(),使用for i,_ := range menu{ if i == espect {...}}
实现get()