我用Go为API写了一些关于“Go Web Development Cookbook.pdf”的代码。我在运行代码时遇到错误。我用切片声明了一个罢工和首字母,在切片中我做了两个项目切片,但是当我去这个时,它显示“函数体外的非声明语句”,我在互联网上搜索了解决方案。这是我的代码:
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 路由 = 路由”行表示错误。
墨色风雨
相关分类