我用Go为API写了一些关于“Go Web Development Cookbook.pdf”的代码。我在运行代码时遇到错误。我用切片声明了一个罢工和首字母,在切片中我做了两个项目切片,但是当我去这个时,它显示“函数体外的非声明语句”,我在互联网上搜索了解决方案。这是我的代码:package mainimport( "fmt" "encoding/json" "log" "net/http" "github.com/gorilla/mux")const( CONN_HOST = "localhost" CONN_PORT = "8080")type Route struct{ Name string Method string Pattern string HandlerFunc http.HandlerFunc}type Routes [] Routevar routes = Routes{ Route { "getEmployees", "GET", "/employees", getEmployees, }, Route { "getEmployee", "GET", "/employee/{id}", getEmployee, },}type Employee struct{ Id string `json:"id"` FirstName string `json:"firstName"` LastName string `json:"lastName"`}type Employees []Employeevar employees []Employeefunc init() { employees = employees { Employee{Id: "1", FirstName: "Foo", LastName: "Bar"}, Employee{Id: "2", FirstName: "Baz", LastName: "Qux"}, }}func getEmployees(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(employees)}func getEmployee(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] for _, employee := range employees { if employee.Id == id { if err := json.NewEncoder(w).Encode(employee); err != nil { log.Print("error getting requested employee :: ", err) } } }}func AddRoutes(router *mux.Router) *mux.Router { for _, route := range routes { router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(route.HandlerFunc) } return router}func main() { muxRouter := mux.NewRouter().StrictSlash(true) router := AddRoutes(muxRouter) err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router) if err != nil { log.Fatal("error starting http server :: ", err) return }}“var 路由 = 路由”行表示错误。
1 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
你的代码格式有问题,在你需要保持放置大括号的约定,你不能把它放在另一行,你需要这样做:Go
var routes = Routes{
Route{
"getEmployees",
"GET",
"/employees",
getEmployees,
},
Route{
"getEmployee",
"GET",
"/employee/{id}",
getEmployee,
},
}
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报
0/150
提交
取消