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.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
820
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
Django's GeneratedField by example - DjangoCon US 2025
pauloxnet
0
150
AWSを利用する上で知っておきたい名前解決のはなし(10分版)
nagisa53
10
3.1k
AWSで始める実践Dagster入門
kitagawaz
1
620
OCI Oracle Database Services新機能アップデート(2025/06-2025/08)
oracle4engineer
PRO
0
140
Practical Agentic AI in Software Engineering
uzyn
0
110
5分でカオスエンジニアリングを分かった気になろう
pandayumi
0
240
エラーとアクセシビリティ
schktjm
1
1.3k
ハードウェアとソフトウェアをつなぐ全てを内製している企業の E2E テストの作り方 / How to create E2E tests for a company that builds everything connecting hardware and software in-house
bitkey
PRO
1
130
EncryptedSharedPreferences が deprecated になっちゃった!どうしよう! / Oh no! EncryptedSharedPreferences has been deprecated! What should I do?
yanzm
0
330
大「個人開発サービス」時代に僕たちはどう生きるか
sotarok
20
10k
Oracle Base Database Service 技術詳細
oracle4engineer
PRO
9
73k
Codeful Serverless / 一人運用でもやり抜く力
_kensh
7
420
Featured
See All Featured
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
12
1.1k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
15
1.6k
Faster Mobile Websites
deanohume
309
31k
A better future with KSS
kneath
239
17k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
46
7.6k
Building a Scalable Design System with Sketch
lauravandoore
462
33k
The Invisible Side of Design
smashingmag
301
51k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Agile that works and the tools we love
rasmusluckow
330
21k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
9
810
Testing 201, or: Great Expectations
jmmastey
45
7.7k
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を使って切り替え ましょう
ご清聴ありがとうございました!