我尝试在线进行一些教程,但是当我声明的对象切片无法实例化时出现麻烦
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
// Article type
type Article struct {
Title string `json:"title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
// Articles is array that holds Article type
// var Articles []Article
var Articles []Article
func allArticles(w http.ResponseWriter, r *http.Request) {
var articles = Articles{
Article{Title: "Test 1", Desc: "Desc", Content: "Content"},
Article{Title: "Test 2", Desc: "Desc 2", Content: "Content 2"},
}
fmt.Println("Endpoint hit: returnAllArticle")
json.NewEncoder(w).Encode(articles)
}
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the HomePage")
fmt.Println("Endpoint hit: homePage")
}
func handleRequest() {
http.HandleFunc("/", homePage)
http.HandleFunc("/articles", allArticles)
log.Fatal(http.ListenAndServe(":8888", nil))
}
func main() {
handleRequest()
}
它总是在第22行说错误
var articles = Articles{
有错误消息
Articles is not a type of go
如果我不做声明,就像
var articles = []Article{ ....
很好,但是我想使用全局变量