用golang写一个bolg的列表接口
package main
import ( "encoding/json" "fmt" "net/http" )
type Blog struct {
Title string json:"title"
Content string json:"content"
}
type Blogs []Blog
var blogList Blogs
func init() { blogList = Blogs{ Blog{Title: "Blog 1", Content: "Content of blog 1"}, Blog{Title: "Blog 2", Content: "Content of blog 2"}, Blog{Title: "Blog 3", Content: "Content of blog 3"}, } }
func main() { http.HandleFunc("/blogs", getBlogs) fmt.Println("Listening on port 8080...") http.ListenAndServe(":8080", nil) }
func getBlogs(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(blogList) }
原文地址: https://www.cveoy.top/t/topic/rA7 著作权归作者所有。请勿转载和采集!