LoginSignup
1
0

More than 3 years have passed since last update.

Goのnetパッケージを理解する~2日目~

Posted at

はじめに

この記事は、Goのnetパッケージを理解する~1日目~の二日目の記事です。

今回は、POSTやGETの処理・htmlの出力をしていきます。

ソースコード

main.go
package main

import (
    "fmt"
    "log"
    "net/http"
    "text/template"
    "time"
)

type Host struct {
    Title string
    Date  time.Time
    Text  string
}

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/temp", handlerTemp)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "GET":
        fmt.Fprint(w, "Hello GET")
    case "POST":
        fmt.Fprint(w, "Hello POST")
    default:
        fmt.Fprint(w, "Hello")
    }
}

func handlerTemp(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("template/index.html")
    if err != nil {
        log.Fatalf("template ERROR")
    }
    host := Host{
        Title: "テストタイトル",
        Date:  time.Now(),
        Text:  "これは、netパッケージの練習です。",
    }

    t.Execute(w, host)
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Test Page
    <form method="POST" action="/">
        <button type="submit">POST</button>
    </form>

    <p>{{ .Title }}</p>
    <p>{{ .Date }}</p>
    <p>{{ .Text }}</p>
</body>
</html>

前回のコードを引用して作成しました。
関数一つ一つ解説していきます。

main関数

ここはほぼ前回と同じ。
8080番ポートでサーバの起動をしています。
/tempってのを追加したくらい

handler関数

前回とは大きく変更しました。handlerに飛ばされてくるメソッドをswitch文で捌いています。

この書き方は、同じ関数を引数にとっても、メソッドが異なるため、正常な動作をしてくれます。
(なんとなくかっこいい感じもする)

今回は、/に対するメソッドを確認したかったので、このように書きました。

handlerTemp関数

今回の肝の関数。
ここで、htmlの出力系の処理をしています。

まず、変数tを宣言して、template.ParseFiles("template/index.html")を指定してます。

これにより、templateディレクトリにあるindex.htmlを出力しますよーって言っている。

index.htmlのコードにもあるように、{{ .hoge }}みたいにテンプレートを扱っているので、Hostを構造体として作成し、定義している。

最後のt.Executeでhostを返している

実行してみる

/にアクセスしてみる

image.png

GETメソッドのため、print文がHello GETになっている

/tempにアクセスしてみる

image.png

hostの内容が出力されていることがわかる。ここで、POSTボタンで/にアクセスしてみる

image.png
POSTでアクセスしたので、print文がHello POSTになっている事がわかる。

まとめ

Goでなにか作るときは、ginとかechoを使ってアプリケーション開発してたんですが、netパッケージもアプリケーション開発以外にも有効に使えるので、これからも継続的にメモとして書いていきます。

netパッケージ。結構いい感じやん。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0