Created
August 5, 2014 08:18
-
-
Save sudix/a56074d8d941473e9137 to your computer and use it in GitHub Desktop.
golang http json response sample [Super-easy JSON HTTP responses, in Go](http://nesv.blogspot.jp/2012/09/super-easy-json-http-responses-in-go.html)
This file contains 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" | |
"fmt" | |
"net/http" | |
) | |
type Response map[string]interface{} | |
func (r Response) String() string { | |
b, err := json.Marshal(r) | |
if err != nil { | |
s := "" | |
return s | |
} | |
s := string(b) | |
return s | |
} | |
func DefaultHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "Hello, HTTP!!!") | |
} | |
func SeeYouHandler(w http.ResponseWriter, r *http.Request) { | |
name := r.FormValue("name") | |
fmt.Fprintf(w, "See you, %s!!!", name) | |
} | |
func JsonHandler(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
fmt.Fprint(w, Response{"success": true, "message": "Hello!"}) | |
return | |
} | |
func main() { | |
http.HandleFunc("/", DefaultHandler) | |
http.HandleFunc("/seeyou", SeeYouHandler) | |
http.HandleFunc("/json", JsonHandler) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment