$30 off During Our Annual Pro Sale. View Details »
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Goで作る初めてのHTTPサーバー
Search
from-unknown
April 17, 2018
Technology
1
1.7k
Goで作る初めてのHTTPサーバー
ツールを作ったことがあるレベルの初心者がHTTPサーバーを開発している時に思った疑問と調べた結果をまとめています。
from-unknown
April 17, 2018
Tweet
Share
More Decks by from-unknown
See All by from-unknown
Goで作ったWebAssemblyで画像加工
fromunknown
1
850
GoでWebAssembly
fromunknown
0
1.4k
Golang+Firestore
fromunknown
1
1.4k
NGO APIを支える技術
fromunknown
0
150
Other Decks in Technology
See All in Technology
初めてのDatabricks AI/BI Genie
taka_aki
0
230
AI時代の新規LLMプロダクト開発: Findy Insightsを3ヶ月で立ち上げた舞台裏と振り返り
dakuon
0
280
mairuでつくるクレデンシャルレス開発環境 / Credential-less development environment using Mailru
mirakui
5
560
Haskell を武器にして挑む競技プログラミング ─ 操作的思考から意味モデル思考へ
naoya
7
1.6k
日本Rubyの会: これまでとこれから
snoozer05
PRO
4
190
ExpoのインダストリーブースでみたAWSが見せる製造業の未来
hamadakoji
0
170
多様なデジタルアイデンティティを攻撃からどうやって守るのか / 20251212
ayokura
0
490
Identity Management for Agentic AI 解説
fujie
0
140
コンテキスト情報を活用し個社最適化されたAI Agentを実現する4つのポイント
kworkdev
PRO
1
1.6k
.NET 10の概要
tomokusaba
0
120
AWS re:Invent 2025~初参加の成果と学び~
kubomasataka
0
150
S3を正しく理解するための内部構造の読解
nrinetcom
PRO
3
190
Featured
See All Featured
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
0
2.2k
AI Search: Implications for SEO and How to Move Forward - #ShenzhenSEOConference
aleyda
1
1k
The Curious Case for Waylosing
cassininazir
0
190
The Limits of Empathy - UXLibs8
cassininazir
1
190
Design of three-dimensional binary manipulators for pick-and-place task avoiding obstacles (IECON2024)
konakalab
0
310
Imperfection Machines: The Place of Print at Facebook
scottboms
269
13k
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
400
Everyday Curiosity
cassininazir
0
110
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
180
Navigating Weather and Climate Data
rabernat
0
44
Faster Mobile Websites
deanohume
310
31k
The #1 spot is gone: here's how to win anyway
tamaranovitovic
1
860
Transcript
Goで作る初めてのHTTPサーバー @from_unknown
前提 発表者のスキルはこんな感じです。 • Goでいくつかツールを作った事はある • Goでサーバーサイドは書いた事がない • PHPでサーバーサイドは書いた事はある ですので、今回はこれからGoでHTTPサーバーを書いてみたい 初心者の方向けの話になります。
GoでHTTPサーバーを立てるには? • Apacheやnginxが必要? • サーバーのソースはどんな感じで書くの? • htmlはどこに書くの? • Cookieやセッションはどう扱うの? •
本番環境と開発環境の切り替えはどうやるの?
Apacheやnginxが必要? Golangは標準ライブラリでHTTPサーバーが提供されているの で、なくても動作しますがあった方がよいです。 理由: • アクセスログを出力してくれる • 静的ページの出力はApacheに任せられる • 複数サービスを1つのサーバーでホストする時にApache側で
捌ける
Apacheやnginxを使う場合 • リバースプロキシでGolangに流す ◦ GolangはHTTPサーバーとして実行する ▪ サーバーに直アクセス可能 ◦ 必要なヘッダーはApacheから追加する様に設定する ◦
間にキャッシュサーバーなどを挟むことも可能 • FastCGIでGolangを呼び出す ◦ GolangはFastCGIで実装し、実行する ▪ サーバーに直アクセス不可 ◦ FastCGI側がアクセスに応じて自動でGolangのプロセスを立ち 上げられる
サーバーのソースはどんな感じで書くの? package main import ( "fmt" "log" "net/http" ) func
handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ※公式のWikiを作るサンプルからコピー https://golang.org/doc/articles/wiki/
サーバーのソースはどんな感じで書くの? package main import ( "fmt" "log" "net/http" ) func
handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } URLのパスが”/”の時にfunc handlerを実行する
サーバーのソースはどんな感じで書くの? package main import ( "fmt" "log" "net/http" ) func
handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ResponseWriterに、文言+URLのパス の値(”/”以下全て)を付けて書き込む これがサーバーからの応答のBody部と なる
サーバーのソースはどんな感じで書くの? package main import ( "fmt" "log" "net/http" ) func
handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ポート8080でアクセスを受 け付ける 異常時はログを出力して終 了する
APIを書く時はもちろんこれだけでは足りない http.HandleFunc("/api/createuser", func(w http.ResponseWriter, r *http.Request) { if r.Method ==
"OPTIONS" { headers := w.Header() headers.Add("Access-Control-Allow-Origin", "*") headers.Add("Vary", "Origin") … headers.Add("Access-Control-Allow-Methods", "GET, POST,OPTIONS") w.WriteHeader(http.StatusOK) } else { createUserHandler(w, r) } return })
APIを書く時はもちろんこれだけでは足りない http.HandleFunc("/api/createuser", func(w http.ResponseWriter, r *http.Request) { if r.Method ==
"OPTIONS" { headers := w.Header() headers.Add("Access-Control-Allow-Origin", "*") headers.Add("Vary", "Origin") … headers.Add("Access-Control-Allow-Methods", "GET, POST,OPTIONS") w.WriteHeader(http.StatusOK) } else { createUserHandler(w, r) } return }) CORSのpreflightで 来る”OPTIONS”も ちゃんと捌きましょう
htmlはどこに書くの? テンプレートファイルを作成して、変数を埋め込めます。 例: <h1>{{.Title}}</h1> <p>[<a href="/edit/{{.Title}}">edit</a>]</p> <div>{{printf "%s" .Body}}</div> 変数や簡単な処理などを
埋め込んでいます
テンプレートファイルの出力の仕方 例: func renderTemplate(w http.ResponseWriter, p *Page) { t, _
:= template.ParseFiles("template.html") t.Execute(w, p) } テンプレートファイルをパースしてExecuteします。 テンプレ内でloopしたり関数を埋め込んだりも可能です。
Cookieやセッションはどう扱うの? Cookieは簡単に作れますが、セッションマネージャーは標準では 用意されていません。 以下のライブラリがセッションを提供しています。 他にもググったら色々あるようなので、もしデファクトスタンダード があれば教えてください。 http://www.gorillatoolkit.org/ https://github.com/icza/session
Cookieのセットの仕方 ※wはhttp.ResponseWriterです sampleCookie := &http.Cookie{ Name: “sample”, Value: “sample”, }
http.SetCookie(w, sampleCookie) Cookieには上記以外にもMaxAgeなどの設定が追加可能です。
本番環境と開発環境の切り替えはどうやるの? • 環境変数で切り替える ◦ Init関数(main関数より先に呼ばれる関数)内で環境変数 を取得し、本番か開発かで値を切り替える • build variantsで切り替える ◦
ソースの一番上部にbuild variantsを記載しておく ◦ tagを指定することで開発時のみや本番時のみだけビルド に含まれるファイルが作成出来る
build variantsの例 // +build debug ←debugタグの時のみ含まれる // +build !debug ←debugタグ以外の時のみ含まれる debugタグのファイルが含まれるビルド go
build -tags debug [file] debugタグのファイルが含まれないビルド go build [file]
まとめ • 単体でも動作しますがApacheやnginxを入れましょう • ロジックからサーバーの設定まで、やりたいことは全てソース に書きます • テンプレートも用意されています • Cookieはありますがセッションは標準で提供されていないの
で、ライブラリを導入しましょう • 環境の切り替えは環境変数かbuild variantsを使って切り替え ましょう
ご清聴ありがとうございました!