Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Created August 27, 2014 07:32
Show Gist options
  • Save kamatama41/291289f1c1990560b031 to your computer and use it in GitHub Desktop.
Save kamatama41/291289f1c1990560b031 to your computer and use it in GitHub Desktop.
A tour of Go #58( http://go-tour-jp.appspot.com/#58 )
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