Translation Go htttp Response Code Snippet

Source: Internet
Author: User
Tags response code
This is a creation in Article, where the information may have evolved or changed.

Catalogue [−]

    1. Send header only
    2. return normal text
    3. Return JSON data
    4. return XML data
    5. File Services
    6. Using HTML templates
    7. Using HTML templates to generate strings
    8. Using nested templates

Original: HTTP Response Snippets for Go by Alex Edwards.

Inspired by Rails layouts and rendering, I think it's a good idea to write a collection of code snippets about the Go HTTP response, which can be used to illustrate the use of common HTTP response in Go Web applications.

Send header only

123456789101112131415
 Package mainimport (  "Net/http")func Main () {  http. Handlefunc ("/", foo)  http. Listenandserve (":"nil)}func foo (w http). Responsewriter, R *http. Request) {  w.header (). Set ("Server""A Go Web Server")  w.writeheader}

Test:

12345
$ curl-i localhost:http/1.1 okserver:a Go Web servercontent-type:text/plain; charset=utf-80

return normal text

1234567891011121314
 Package mainimport (  "Net/http")func Main () {  http. Handlefunc ("/", foo)  http. Listenandserve (":"nil)}func foo (w http). Responsewriter, R *http. Request) {  w.write ([]byte("OK")}

Test:

123456
$ curl-i localhost:http/1.1 Okcontent-type:text/plain; charset=utf-82OK

Return JSON data

1234567891011121314151617181920212223242526272829
 PackageMainImport("Encoding/json"  "Net/http")typeProfilestruct{NamestringHobbies []string}funcMain () {http. Handlefunc ("/", foo) http. Listenandserve (":",Nil)}funcFoo (w http. Responsewriter, R *http. Request) {profile: = profile{"Alex", []string{"Snowboarding","Programming"}} js, err: = json. Marshal (Profile)ifErr! =Nil{http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} w.header (). Set ("Content-type","Application/json") W.write (JS)}

Test:

123456
$ curl-i localhost:http/1.1, "Name":"Alex", Hobbies": ["Snowboarding","programming"]}

return XML data

1234567891011121314151617181920212223242526272829
 PackageMainImport("Encoding/xml"  "Net/http")typeProfilestruct{NamestringHobbies []string ' xml: ' Hobbies>hobby '}funcMain () {http. Handlefunc ("/", foo) http. Listenandserve (":",Nil)}funcFoo (w http. Responsewriter, R *http. Request) {profile: = profile{"Alex", []string{"Snowboarding","Programming"}} x, err: = XML. Marshalindent (Profile,"","  ")ifErr! =Nil{http. Error (W, err. Error (), HTTP. Statusinternalservererror)return} w.header (). Set ("Content-type","Application/xml") W.write (x)}

Test:

123456789101112
$ curl-i localhost:http/1.1<Profile>  <name>alex </Name>  <Hobbies>    <Hobby>snowboarding</Hobby>    <Hobby>programming< /hobby>  </Hobbies></Profile>

File Services

1234567891011121314151617
 Package mainimport (  "net/http"  "path")func Main () {  http . Handlefunc ("/", foo)  http. Listenandserve (":"nil)}func foo (w http). Responsewriter, R *http. Request) {  //Assuming want to serve a photo at ' Images/foo.png '  fp: = path. Join ("Images""foo.png")  http. Servefile (W, R, FP)}

Test:

123456
$ curl-i localhost:http/1.1-236717: : + GMT

Using HTML templates

Template file: templates/index.html

Templates/index.html
12
<H1>Hello {{. Name}}</h1><p>Lorem ipsum dolor sit amet, consectetur adipisicing Elit. </P>
1234567891011121314151617181920212223242526272829303132
 PackageMainImport("Html/template"  "Net/http"  "Path")typeProfilestruct{NamestringHobbies []string}funcMain () {http. Handlefunc ("/", foo) http. Listenandserve (":",Nil)}funcFoo (w http. Responsewriter, R *http. Request) {profile: = profile{"Alex", []string{"Snowboarding","Programming"}} fp: = path. Join ("Templates","Index.html") Tmpl, err: = template. Parsefiles (FP)ifErr! =Nil{http. Error (W, err. Error (), HTTP. Statusinternalservererror)return}ifERR: = Tmpl. Execute (w, profile); Err! =Nil{http. Error (W, err. Error (), HTTP. Statusinternalservererror)}}

Test:

1234567
$ curl-i localhost:http/1.1 okcontent-type:text/html; charset=utf-8

Using HTML templates to generate strings

In addition to the above http.ResponseWriter as the template of the execution parameters, you can also use buffer to get the result of rendering.

1234567
New (bytes. Buffer)ifnil {  http. Error (W, err. Error (), HTTP. Statusinternalservererror)}templatestring: = buf. String () ...

Using nested templates

Files: templates/layout.html

templates/layout.html
12345678

Files: templates/index.html

templates/index.html
123456
{{define ' title '}} An example layout{{end}} {{define "content"}}<h1>Hello {{. Name}}</h1><p>Lorem ipsum dolor sit amet, consectetur adipisicing Elit. </P> {{End}}
1234567891011121314151617181920212223242526272829303132333435
 PackageMainImport("Html/template"  "Net/http"  "Path")typeProfilestruct{NamestringHobbies []string}funcMain () {http. Handlefunc ("/", foo) http. Listenandserve (":",Nil)}funcFoo (w http. Responsewriter, R *http. Request) {profile: = profile{"Alex", []string{"Snowboarding","Programming"}} LP: = Path. Join ("Templates","Layout.html") fp: = path. Join ("Templates","Index.html")//Note that the layout file must is the first parameter in ParsefilesTmpl, err: = template. Parsefiles (LP, FP)ifErr! =Nil{http. Error (W, err. Error (), HTTP. Statusinternalservererror)return}ifERR: = Tmpl. Execute (w, profile); Err! =Nil{http. Error (W, err. Error (), HTTP. Statusinternalservererror)}}

Test:

1234567891011121314
$ curl-i localhost:http/1.1 okcontent-type:text/html; charset=utf-8
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.