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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshubo1989/article/details/79193383

号外!!!号外!!!

截至 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包中的几个方法:

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

例子,main.go

package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":8080", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Server", "A Go Web Server")
    w.WriteHeader(200)
}

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

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

返回文本

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

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

例子,main.go

package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":8080", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("I am Gopher"))
}

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

curl -i localhost:8080
HTTP/1.1 200 OK
Date: Mon, 29 Jan 2018 03:02:00 GMT
Content-Length: 11
Content-Type: text/plain; charset=utf-8

I am Gopher

返回JSON

返回json才是正路子。

例子,main.go:

package main

import (
    "encoding/json"
    "net/http"
)

type Profile struct {
    Name    string   `json:"name"`
    Hobbies []string `json:"hobbies"`
}

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":8080", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {
    profile := Profile{"SuperWang", []string{"football", "programming"}}

    js, err := json.Marshal(profile)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    w.Write(js)
}

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

curl -i localhost:8080
HTTP/1.1 200 OK
Content-Type: application/json
Date: Mon, 29 Jan 2018 03:10:52 GMT
Content-Length: 57

{"name":"SuperWang","hobbies":["football","programming"]}

返回XML

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

例子,main.go:

package main

import (
    "encoding/xml"
    "net/http"
)

type Profile struct {
    Name    string
    Hobbies []string `xml:"Hobbies>Hobby"`
}

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":8080", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {
    profile := Profile{"SuperWang", []string{"football", "programming"}}

    x, err := xml.MarshalIndent(profile, "", "  ")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/xml")
    w.Write(x)
}

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

curl -i localhost:8080
HTTP/1.1 200 OK
Content-Type: application/xml
Date: Mon, 29 Jan 2018 03:16:00 GMT
Content-Length: 129

<Profile>
  <Name>SuperWang</Name>
  <Hobbies>
    <Hobby>football</Hobby>
    <Hobby>programming</Hobby>
  </Hobbies>
</Profile>

返回文件

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

例子,main.go:

package main

import (
    "net/http"
    "path"
)

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":8080", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {
    fp := path.Join("images", "foo.png")
    http.ServeFile(w, r, fp)
}

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

返回HTML

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

例子,main.go:

package main

import (
    "html/template"
    "net/http"
    "path"
)

type Profile struct {
    Name    string
    Hobbies []string
}

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":8080", nil)
}

func foo(w http.ResponseWriter, r *http.Request) {
    profile := Profile{"SpuerWang", []string{"snowboarding", "programming"}}

    fp := path.Join("templates", "index.html")
    tmpl, err := template.ParseFiles(fp)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    if err := tmpl.Execute(w, profile); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

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

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

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

猜你喜欢

转载自blog.csdn.net/wangshubo1989/article/details/79193383
今日推荐