A Tour of Go55~62学習メモ

  • インターフェース型のerrorError() stringという文字列を返すメソッドが定義されている
  • 返すエラーを自分で定義する際はstructを定義して、Error() stringのメソッドを実装
  • httpパッケージからHTTPリクエストの処理機能が提供されている
  • インターフェース型のHandlerにServeHTTP(w ResponseWriter, r *Request)というメソッドが定義されている

A Tour of Go58の解答

package main

import (
	"fmt"
	"net/http"
)

type String string
type Struct struct {
	Greeting string
	Punct string
	Who string	
}

func (str String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%s", str)
}

func (str *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%s%s%s", str.Greeting, str.Punct, str.Who)
}

func init() {
	http.Handle("/string", String("I'm a frayed knot."))
	http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
	http.ListenAndServe("localhost:4000", nil)
}

悩んだところ

  • yamlファイルのscript: _go_appの部分はscriptの前にスペース2個。pythonはこういうところが厳密なので注意。
  • func init()で書かなければならない。今までmain()でチュートリアルが進んでいたのでここで詰まってしまった。
  • fmt.Fprintfを使わないと表示されないので注意
  • http://localhost:4000/string, structでアクセスしないといけないのにhttp://localhost:4000だけでアクセスしていた