Created
August 27, 2014 07:32
-
-
Save kamatama41/291289f1c1990560b031 to your computer and use it in GitHub Desktop.
A tour of Go #58( http://go-tour-jp.appspot.com/#58 )
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" | |
"fmt" | |
"net/http" | |
) | |
type String string | |
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
// 標準出力のみ | |
fmt.Println(s) | |
} | |
type Struct struct { | |
Greeting string | |
Punct string | |
Who string | |
} | |
func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
// jsonを返す | |
js, err := json.Marshal(s) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.Write(js) | |
} | |
func main() { | |
// your http.Handle calls here | |
http.Handle("/string", String("I'm a frayed knot.")) | |
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"}) | |
http.ListenAndServe("localhost:4000", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment