Created
September 20, 2017 06:54
-
-
Save chaosx/94ed418168ca83e67d26a202a130c433 to your computer and use it in GitHub Desktop.
Golang http response json (http://www.alexedwards.net/blog/golang-response-snippets#json)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "net/http" | |
| ) | |
| type Profile struct { | |
| Name string | |
| Hobbies []string | |
| } | |
| func main() { | |
| http.HandleFunc("/", foo) | |
| http.ListenAndServe(":3000", nil) | |
| } | |
| func foo(w http.ResponseWriter, r *http.Request) { | |
| profile := Profile{"Alex", []string{"snowboarding", "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) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment