Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
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.6k
Goで作る初めてのHTTPサーバー
ツールを作ったことがあるレベルの初心者がHTTPサーバーを開発している時に思った疑問と調べた結果をまとめています。
from-unknown
April 17, 2018
Tweet
Share
More Decks by from-unknown
See All by from-unknown
Goで作ったWebAssemblyで画像加工
fromunknown
1
750
GoでWebAssembly
fromunknown
0
1.3k
Golang+Firestore
fromunknown
1
1.3k
NGO APIを支える技術
fromunknown
0
140
Other Decks in Technology
See All in Technology
1等無人航空機操縦士一発試験 合格までの道のり ドローンミートアップ@大阪 2024/12/18
excdinc
0
170
KubeCon NA 2024 Recap / Running WebAssembly (Wasm) Workloads Side-by-Side with Container Workloads
z63d
1
250
TSKaigi 2024 の登壇から広がったコミュニティ活動について
tsukuha
0
160
サイバー攻撃を想定したセキュリティガイドライン 策定とASM及びCNAPPの活用方法
syoshie
3
1.3k
事業貢献を考えるための技術改善の目標設計と改善実績 / Targeted design of technical improvements to consider business contribution and improvement performance
oomatomo
0
100
どちらを使う?GitHub or Azure DevOps Ver. 24H2
kkamegawa
0
890
スタートアップで取り組んでいるAzureとMicrosoft 365のセキュリティ対策/How to Improve Azure and Microsoft 365 Security at Startup
yuj1osm
0
230
Amazon Kendra GenAI Index 登場でどう変わる? 評価から学ぶ最適なRAG構成
naoki_0531
0
120
PHPからGoへのマイグレーション for DMMアフィリエイト
yabakokobayashi
1
170
ずっと昔に Star をつけたはずの思い出せない GitHub リポジトリを見つけたい!
rokuosan
0
150
Oracle Cloud Infrastructure:2024年12月度サービス・アップデート
oracle4engineer
PRO
0
210
Microsoft Azure全冠になってみた ~アレを使い倒した者が試験を制す!?~/Obtained all Microsoft Azure certifications Those who use "that" to the full will win the exam! ?
yuj1osm
2
110
Featured
See All Featured
A better future with KSS
kneath
238
17k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
0
98
Stop Working from a Prison Cell
hatefulcrawdad
267
20k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.3k
Making Projects Easy
brettharned
116
5.9k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
45
2.2k
Gamification - CAS2011
davidbonilla
80
5.1k
Designing for humans not robots
tammielis
250
25k
Statistics for Hackers
jakevdp
796
220k
Speed Design
sergeychernyshev
25
670
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
28
2.1k
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を使って切り替え ましょう
ご清聴ありがとうございました!