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
830
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
実装で解き明かす並行処理の歴史
zozotech
PRO
1
530
AIAgentの限界を超え、 現場を動かすWorkflowAgentの設計と実践
miyatakoji
0
150
E2Eテスト設計_自動化のリアル___Playwrightでの実践とMCPの試み__AIによるテスト観点作成_.pdf
findy_eventslides
1
480
組織観点からIAM Identity CenterとIAMの設計を考える
nrinetcom
PRO
1
190
SOC2取得の全体像
shonansurvivors
1
410
AI駆動開発を推進するためにサービス開発チームで 取り組んでいること
noayaoshiro
0
220
【Oracle Cloud ウェビナー】クラウド導入に「専用クラウド」という選択肢、Oracle AlloyとOCI Dedicated Region とは
oracle4engineer
PRO
3
120
研究開発部メンバーの働き⽅ / Sansan R&D Profile
sansan33
PRO
3
20k
英語は話せません!それでも海外チームと信頼関係を作るため、対話を重ねた2ヶ月間のまなび
niioka_97
0
130
職種別ミートアップで社内から盛り上げる アウトプット文化の醸成と関係強化/ #DevRelKaigi
nishiuma
2
140
AWS 잘하는 개발자 되기 - AWS 시작하기: 클라우드 개념부터 IAM까지
kimjaewook
0
110
小学4年生夏休みの自由研究「ぼくと Copilot エージェント」
taichinakamura
0
490
Featured
See All Featured
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
252
21k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
229
22k
Making the Leap to Tech Lead
cromwellryan
135
9.5k
The Language of Interfaces
destraynor
162
25k
Navigating Team Friction
lara
189
15k
Art, The Web, and Tiny UX
lynnandtonic
303
21k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
7
890
The Power of CSS Pseudo Elements
geoffreycrofte
79
6k
Fantastic passwords and where to find them - at NoRuKo
philnash
52
3.4k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
15
1.7k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
9
580
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
333
22k
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を使って切り替え ましょう
ご清聴ありがとうございました!