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
730
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
いまいまMySQL2024 @ OSC Nagaoka
sakaik
2
170
コード✕AIーソフトウェア開発者のための生成AI実践入門~
yuhattor
4
920
From naive to advanced RAG: the complete guide
glaforge
0
490
地域DXにおけるGrafana活用事例
wacky
0
350
多数のWebサービスをECS/Fargate構成で効率よく構築・運用するなら copilot-cli
interu
2
130
道具としてのGraphQLから見る用途や解決する課題
saboyutaka
0
100
塩野義製薬様のAWS統合管理戦略:Organizations設計と運用の具体例
tkikuchi
0
280
これはPerl? それともRuby? クイズ〜〜〜〜〜!!!- Perl or Ruby Quiz
moznion
3
2.1k
テクニカルライターのチームで「目標」をどう決めたか / MVV for a Team of Technical Writers
lycorptech_jp
PRO
3
140
Perlで始めるeBPF: 自作Loaderの作り方 / Getting started with eBPF in Perl_How to create your own Loader
takehaya
1
1.1k
AWS Lambda と Amazon SQS で「わかった気になれる」FreeRTOS 入門
soracom
PRO
2
110
入社半年(合計1年)でGoogle Cloud 認定を全冠した秘訣🤫
risatube
1
260
Featured
See All Featured
It's Worth the Effort
3n
183
27k
Making the Leap to Tech Lead
cromwellryan
131
8.9k
Build your cross-platform service in a week with App Engine
jlugia
229
18k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
105
48k
Code Review Best Practice
trishagee
63
17k
The Pragmatic Product Professional
lauravandoore
31
6.2k
StorybookのUI Testing Handbookを読んだ
zakiyama
26
5.1k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
167
49k
How To Stay Up To Date on Web Technology
chriscoyier
787
250k
Bootstrapping a Software Product
garrettdimon
PRO
304
110k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
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を使って切り替え ましょう
ご清聴ありがとうございました!