我是刚来的初学者,我的学习还在继续。我和golang一起为API编写了一个关于“goweb开发”的代码食谱.pdf". 我在运行代码时遇到了一个错误。我用slice声明了一个stroked和initial,在slice中我做了两个slice项,但当我转到这里时,它显示了"non-declaration函数体外的语句“我在互联网上搜索了解决方案。这是我的密码
package main
import
(
"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 [] Route
var 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 []Employee
var employees []Employee
func 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 routes=routes”行表示错误。请任何人帮帮我。