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-Swagger in production
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Ilya Kaznacheev
June 25, 2020
Programming
560
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Go-Swagger in production
Ilya Kaznacheev
June 25, 2020
More Decks by Ilya Kaznacheev
See All by Ilya Kaznacheev
Road to four nines
dreamworm
0
30
Many Layers of Availability
dreamworm
0
110
Stateful Solutions: A Hands-On Guide to FSM in Golang
dreamworm
0
210
CQRS
dreamworm
0
190
Building a Cloud-Native PaaS
dreamworm
0
170
Distributed System State Management: When Transactions Are Long and SLA Is High
dreamworm
0
160
How To Create Saga-Free Distributed Transactions
dreamworm
0
83
Architectural decisions in building distributed systems
dreamworm
0
46
Распределенные транзакции без саг
dreamworm
0
220
Other Decks in Programming
See All in Programming
5分で問診!Composer セキュリティ健康診断
codmoninc
0
860
ここ半年くらいでAIに作らせたR用ツール
eitsupi
0
360
AWS CDK を「作」ってみた 〜フルスクラッチで見えた CDK の裏側〜 / aws-cdk-from-scratch
gotok365
3
2.8k
jsmini JavaScript Engine を作ってみた話
yosuke_furukawa
PRO
0
290
人間の目はかわらない、だからJPEGは30年もつ
yuzneri
12
18k
AI時代に設計が 最大の生産性レバーになる 意図駆動開発とデータを消さない設計|Don't Delete Your Data or Your Intent — Design as the Deepest Lever in the AI Era
tomohisa
1
650
使用 Meilisearch 建立新聞搜尋工具
johnroyer
0
220
Detecting Compromised CI with eBPF and Cilium Tetragon
lizrice
0
130
Claude Opus 4.6以後の受託開発エンジニアの変化(Claude Code開発ノウハウ大公開スペシャルbyクラスメソッド)
iidatakuma
1
960
komatsuna「分散システムにおけるバグ分析手法」
komatsunaqa
0
230
仕様書を書く前にハーネスを作る - Agent Native開発は「探索を速く、判定を固く」
gotalab555
4
1.5k
なぜ関数型プログラミングで「型」と「証明」が語られるのか #fp_matsuri
kajitack
3
1.1k
Featured
See All Featured
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
480
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
52
6k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
28
3.6k
Test your architecture with Archunit
thirion
1
2.3k
Design in an AI World
tapps
1
270
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.4k
The Cost Of JavaScript in 2023
addyosmani
55
10k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
330
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
600
WCS-LA-2024
lcolladotor
0
790
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
610
Transcript
Go-Swagger in production wins and pitfalls
Ilya Kaznacheev Remote Backend SWE Founder of Golang Voronezh Host
of Z-Namespace podcast Organizer of conference and meetups Coffee geek
what swagger is?
None
SOAP JSON-PRC GraphQL gRPC OData REST
Representational state transfer (REST) is a software architectural style that
defines a set of constraints to be used for creating Web services Wikipedia
None
swagger: "2.0" info: title: Pet API version: "1.0.0" basePath: /api
schemes: - http paths: /pets: get: summary: List all pets parameters: - name: limit in: query description: "How many items to return at one time" required: true type: integer responses: 200: description: an paged array of pets 400: description: unexpected error
None
None
why do we use swagger?
my team trying to sync API changes...
None
go-swagger
code generation swagger generate server -t internal/api --exclude-main
generated code structure internal/api ├ models │ └ ... └
restapi ├ operations │ └ ... ├ configure_<your_service_name>.go ├ doc.go ├ embedded_spec.go └ server.go
our code generation rm -rf internal/api && mkdir -p internal/api
swagger generate server -t internal/api --exclude-main go mod tidy
? and we're all set
NO
there are some problems - go-swagger is a framework, not
a library - plenty of generated types for everything - incompatible with popular http-libraries
let’s fix ’em all!
serving net/http handlers type CustomResponder func(http.ResponseWriter, runtime.Producer) func (c CustomResponder)
WriteResponse(w http.ResponseWriter, p runtime.Producer) { c(w, p) } func MetricsHandler(p instruments.GetMetricsParams) middleware.Responder { return CustomResponder(func(w http.ResponseWriter, _ runtime.Producer) { promhttp.Handler().ServeHTTP(w, p.HTTPRequest) }) }
simple middleware api := operations.NewSwaggerPetstoreAPI(swaggerSpec) api.InstrumentsGetMetricsHandler = instruments.GetMetricsHandlerFunc(MetricsHandler) api.AddMiddlewareFor("GET", "/metrics",
SomeMiddleware) srv := restapi.NewServer(api) srv.Serve()
middleware with custom handler h := api.Serve(nil) r := chi.NewRouter()
r.Use( middleware.Recoverer, ) r.With(AuthMiddleware).Group(func(r chi.Router) { r.Handle("/user/*", h) }) r.Mount("/", h) srv.ConfigureAPI() srv.SetHandler(r) srv.Serve()
setup outside of configure_<your_service_name>.go api.Logger = log.Printf api.HTMLProducer = runtime.TextProducer()
srv := restapi.NewServer(api) srv.EnabledListeners = []string{"http"} srv.Port = conf.HTTPPort srv.Host = conf.HTTPAddr
custom method names /store/order/{orderId}/items: get: tags: - store summary: Find
purchase order items parameters: - name: orderId in: path required: true type: integer func GetOrderItems( param store.GetStoreOrderOrderIDItemsParams, ) middleware.Responder { items, err := getOrderItems(param.OrderID) if err != nil { return store.NewGetStoreOrderOrderIDItemsNotFound() } res := &models.OrderItems{} // // fill resopnse // return store.NewGetStoreOrderOrderIDItemsOK(). WithPayload(res) }
custom method names /store/order/{orderId}/items: get: tags: - store summary: Find
purchase order items operationId: getOrderItems parameters: - name: orderId in: path required: true type: integer func GetOrderItems( param store.GetOrderItemsParams, ) middleware.Responder { items, err := getOrderItems(param.OrderID) if err != nil { return store.NewGetOrderItemsNotFound() } res := &models.OrderItems{} // // fill resopnse // return store.NewGetOrderItemsOK(). WithPayload(res) }
validity checks OrderItems: type: object properties: message: type: string maximum:
3 # swg/internal/api/models internal/api/models/order_items.go:45:55: cannot convert m.Message (type string) to type float64
validity check cheat sheet numbers and integers - multipleOf -
maximum - minimum - exclusiveMaximum - exclusiveMinimum strings - maxLength - minLength - pattern arrays - maxItems - minItems - uniqueItems - maxContains - minContains objects - maxProperties - minProperties - required - dependentRequired any type - type - enum - const
extensions (tricks) x-omitempty x-nullable x-isnullable x-order x-go-custom-tag x-schemes x-go-name x-go-type
x-go-json-string x-go-enum-ci
Shortcuts Error: type: object required: - code - message properties:
code: type: integer message: type: string type APIError struct { code int Payload *models.Error `json:"body,omitempty"` } func (e *APIError) WriteResponse( rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(e.code) producer.Produce(rw, e.Payload) } func RespondError(code int, err error) *APIError { return &APIError{ code: code, Payload: &models.Error{code, err.Error()}, } }
unit tests func GetOrderByID(param store.GetOrderByIDParams) middleware.Responder { order := models.Order{
ID: 123, PetID: 456, Quantity: 20, Status: "approved", } if param.OrderID != order.ID { return store.NewGetOrderByIDNotFound().WithPayload(&models.ErrorMessage{ Code: http.StatusNotFound, Message: http.StatusText(http.StatusNotFound), }) } return store.NewGetOrderByIDOK().WithPayload(&order) }
unit tests tests := []struct { name string req store.GetOrderByIDParams
code int want string }{ { name: "good test", req: store.GetOrderByIDParams{OrderID: 123}, code: 200, want: `{"id":123,"petId":456,"quantity":20,"status":"approved"}`, }, { name: "bad test", req: store.GetOrderByIDParams{OrderID: 456}, code: 404, want: `{"message":"Not Found", "code":404}`, }, }
unit tests for _, tt := range tests { t.Run(tt.name,
func(t *testing.T) { rr := httptest.NewRecorder() GetOrderByID(tt.req).WriteResponse(rr, runtime.JSONProducer()) assert.JSONEq(t, tt.want, rr.Body.String(), "wrong response body") assert.Equal(t, tt.code, rr.Code, "wrong response code") }) }
None
helpful links json-schema.org/specification.html swagger.io/docs/specification/2-0 goswagger.io bit.ly/go-swagger-in-production
ilyakaznacheev