Go实战--Golang Response Snippets: JSON, XML and more(http请求返回值)

前端之家收集整理的这篇文章主要介绍了Go实战--Golang Response Snippets: JSON, XML and more(http请求返回值)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

号外!!!号外!!!

截至 2018 年 1 月 24 日,通过统计 GitHub 上活跃用户的活动情况,对每种语言的排名结果如下:

2018 年要学习的编程语言
观察这种编程语言趋势的最好方法就是,确定具有快速增长的用户群的新兴编程语言:

明显能看到,用户群增长最快的语言分别有:Go,TypeScript,Kotlin 和 Rust。

生命不止,继续 go go go !!!

之前写了不少博客,其中很多都是关于golang web开发,或是golang restful api的。
其中对于http请求,我们需要进行write response,今天就用一篇博客进行介绍。

参考:
http://www.alexedwards.net/blog/golang-response-snippets

只返回header

对于一些请求而言,不需要返回任何的数据,只是返回一个header即可,大大提高了返回服务器响应速度。
先了解一下net/http包中的几个方法

  1. //给一个key设定为响应的value.
  2. func (h Header) Set(key,value string)
  1. // WriteHeader该方法发送HTTP回复的头域和状态码。如果没有被显式调用,第一次调用Write时会触发隐式调用WriteHeader(http.StatusOK)。因此,显示调用WriterHeader主要用于发送错误状态码。
  2. WriteHeader(int)

例子,main.go

  1. package main
  2.  
  3. import (
  4. "net/http"
  5. )
  6.  
  7. func main() {
  8. http.HandleFunc("/",foo)
  9. http.ListenAndServe(":8080",nil)
  10. }
  11.  
  12. func foo(w http.ResponseWriter,r *http.Request) {
  13. w.Header().Set("Server","A Go Web Server")
  14. w.WriteHeader(200)
  15. }

通过curl进行请求:curl -i localhost:8080

  1. curl -i localhost:8080
  2. HTTP/1.1 200 OK
  3. Server: A Go Web Server
  4. Date: Mon,29 Jan 2018 02:52:41 GMT
  5. Content-Length: 0
  6. Content-Type: text/plain; charset=utf-8

返回文本

这个不常用,但是也介绍一下而已。
用到的方法

  1. // Write向连接中写入数据,该数据作为HTTP response的一部分。如果被调用时还没有调用WriteHeader,本方法会先调用
  2. WriteHeader(http.StatusOK)。
  3. //如果Header中没有"Content-Type"键,本方法会使用包函数DetectContentType检查数据的前512字节,将返回值作为该键的值
  4. Write([]byte) (int,error)

例子,main.go

  1. package main
  2.  
  3. import (
  4. "net/http"
  5. )
  6.  
  7. func main() {
  8. http.HandleFunc("/",r *http.Request) {
  9. w.Write([]byte("I am Gopher"))
  10. }

通过curl进行请求:curl -i localhost:8080

  1. curl -i localhost:8080
  2. HTTP/1.1 200 OK
  3. Date: Mon,29 Jan 2018 03:02:00 GMT
  4. Content-Length: 11
  5. Content-Type: text/plain; charset=utf-8
  6.  
  7. I am Gopher

返回JSON

返回json才是正路子。

例子,main.go:

  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "net/http"
  6. )
  7.  
  8. type Profile struct {
  9. Name string `json:"name"`
  10. Hobbies []string `json:"hobbies"`
  11. }
  12.  
  13. func main() {
  14. http.HandleFunc("/",r *http.Request) {
  15. profile := Profile{"SuperWang",[]string{"football","programming"}}
  16.  
  17. js,err := json.Marshal(profile)
  18. if err != nil {
  19. http.Error(w,err.Error(),http.StatusInternalServerError)
  20. return
  21. }
  22.  
  23. w.Header().Set("Content-Type","application/json")
  24. w.Write(js)
  25. }

通过curl进行请求:curl -i localhost:8080

  1. curl -i localhost:8080
  2. HTTP/1.1 200 OK
  3. Content-Type: application/json
  4. Date: Mon,29 Jan 2018 03:10:52 GMT
  5. Content-Length: 57
  6.  
  7. {"name":"SuperWang","hobbies":["football","programming"]}

返回XML

很久之前,很多人讨论xml和json孰是孰非,渐渐地xml越来越被人们遗忘。
但是一些接口还是需要使用xml的,比如xmpp协议。

例子,main.go:

  1. package main
  2.  
  3. import (
  4. "encoding/xml"
  5. "net/http"
  6. )
  7.  
  8. type Profile struct {
  9. Name string
  10. Hobbies []string `xml:"Hobbies>Hobby"`
  11. }
  12.  
  13. func main() {
  14. http.HandleFunc("/","programming"}}
  15.  
  16. x,err := xml.MarshalIndent(profile,""," ")
  17. if err != nil {
  18. http.Error(w,"application/xml")
  19. w.Write(x)
  20. }

通过curl进行请求:curl -i localhost:8080

  1. curl -i localhost:8080
  2. HTTP/1.1 200 OK
  3. Content-Type: application/xml
  4. Date: Mon,29 Jan 2018 03:16:00 GMT
  5. Content-Length: 129
  6.  
  7. <Profile>
  8. <Name>SuperWang</Name>
  9. <Hobbies>
  10. <Hobby>football</Hobby>
  11. <Hobby>programming</Hobby>
  12. </Hobbies>
  13. </Profile>

返回文件

通过接口,返回一张图片,一个文本文件等等,都是很常见的。

例子,main.go:

  1. package main
  2.  
  3. import (
  4. "net/http"
  5. "path"
  6. )
  7.  
  8. func main() {
  9. http.HandleFunc("/",foo)
  10. http.ListenAndServe(":8080",nil)
  11. }
  12.  
  13. func foo(w http.ResponseWriter,r *http.Request) {
  14. fp := path.Join("images","foo.png")
  15. http.ServeFile(w,r,fp)
  16. }

建一个images文件夹,放入foo.png文件,运行,浏览器访问:
http://localhost:8080/

返回HTML

下面是返回一个HTML的网页。

例子,main.go:

  1. package main
  2.  
  3. import (
  4. "html/template"
  5. "net/http"
  6. "path"
  7. )
  8.  
  9. type Profile struct {
  10. Name string
  11. Hobbies []string
  12. }
  13.  
  14. func main() {
  15. http.HandleFunc("/",nil)
  16. }
  17.  
  18. func foo(w http.ResponseWriter,r *http.Request) {
  19. profile := Profile{"SpuerWang",[]string{"snowboarding","programming"}}
  20.  
  21. fp := path.Join("templates","index.html")
  22. tmpl,err := template.ParseFiles(fp)
  23. if err != nil {
  24. http.Error(w,err.Error(),http.StatusInternalServerError)
  25. return
  26. }
  27.  
  28. if err := tmpl.Execute(w,profile); err != nil {
  29. http.Error(w,http.StatusInternalServerError)
  30. }
  31. }

新建文件夹templates,在里面新建文件inde.html:

  1. <h1>Hello {{ .Name }}</h1> <p>一九八四年 庄稼还没收割完;儿子躺在我怀里 睡得那么甜;今晚的露天电影 没时间去看;妻子提醒我 修修缝纫机的踏板</p>

运行,浏览器输入:
http://localhost:8080/

猜你在找的Go相关文章