文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
JSON
JSON is quickly becoming the ubiquitous serialization format for web APIs, so it may be the most relevant when learning how to build web apps using Go. Fortunately, Go makes it simple to work with JSON -- it is extremely easy to turn existing Go structs into JSON using the encoding/json
package from the standard library.
package main
import (
"encoding/json"
"net/http"
)
type Book struct {
Title string `json:"title"`
Author string `json:"author"`
}
func main() {
http.HandleFunc("/", ShowBooks)
http.ListenAndServe(":8080", nil)
}
func ShowBooks(w http.ResponseWriter, r *http.Request) {
book := Book{"Building Web Apps with Go", "Jeremy Saenz"}
js, err := json.Marshal(book)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
Exercises
- Read through the JSON API docs and find out how to rename and ignore fields for JSON serialization.
- Instead of using the
json.Marshal
method, try using thejson.Encoder
API. - Figure our how to pretty print JSON with the
encoding/json
package.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论