Skip to content

Instantly share code, notes, and snippets.

@hiroosak
Last active August 29, 2015 14:04
Show Gist options
  • Save hiroosak/f4d7abe9132db32ac5f2 to your computer and use it in GitHub Desktop.
Save hiroosak/f4d7abe9132db32ac5f2 to your computer and use it in GitHub Desktop.
Go言語でhttpサーバーを立ち上げてHello Worldをする ref: http://qiita.com/taizo/items/bf1ec35a65ad5f608d45
package main
import (
"fmt"
"net/http"
)
type String string
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
func main() {
http.Handle("/", String("Hello World."))
http.ListenAndServe("localhost:8000", nil)
}
package main
import (
"fmt"
"net/http"
)
type String string
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
func main() {
http.Handle("/", String("Hello World."))
http.ListenAndServe("localhost:8000", nil)
}
$ go run server.go
$ open http://localhost:8080 # Macの場合
$ go run server.go
$ open http://localhost:8080 # Macの場合
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
</head>
<body>
{{.Title}} {{.Count}} count
</body>
</html>
package main
import (
"net/http"
"text/template"
)
type Page struct {
Title string
Count int
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
page := Page{"Hello World.", 1}
tmpl, err := template.ParseFiles("layout.html") // ParseFilesを使う
if err != nil {
panic(err)
}
err = tmpl.Execute(w, page)
if err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/", viewHandler) // hello
http.ListenAndServe(":8080", nil)
}
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World")
}
func main() {
http.HandleFunc("/", handler) // ハンドラを登録してウェブページを表示させる
http.ListenAndServe(":8080", nil)
}
package main
import (
"net/http"
"text/template"
)
type Page struct { // テンプレート展開用のデータ構造
Title string
Count int
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
page := Page{"Hello World.", 1} // テンプレート用のデータ
tmpl, err := template.New("new").Parse("{{.Title}} {{.Count}} count") // テンプレート文字列
if err != nil {
panic(err)
}
err = tmpl.Execute(w, page) // テンプレートをジェネレート
if err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/", viewHandler) // hello
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment