Skip to content

Commit

Permalink
Add openapi plugin (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
chokoswitch committed Oct 23, 2023
1 parent 03cec98 commit f0ab668
Show file tree
Hide file tree
Showing 14 changed files with 887 additions and 7 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
with:
go-version-file: go.mod
go-version-file: go.work
cache: true

- name: run checks
Expand Down
6 changes: 4 additions & 2 deletions examples/grpc/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ module github.com/curioswitch/go-docs-handler/examples/grpc

go 1.19

require google.golang.org/protobuf v1.31.0
require (
google.golang.org/grpc v1.57.0
google.golang.org/protobuf v1.31.0
)

require (
github.com/golang/protobuf v1.5.3 // indirect
golang.org/x/net v0.9.0 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 // indirect
google.golang.org/grpc v1.57.0 // indirect
)
2 changes: 1 addition & 1 deletion examples/grpc/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaS
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto v0.0.0-20230526161137-0005af68ea54 h1:9NWlQfY2ePejTmfwUH1OWwmznFa+0kKcHGPDvcPza9M=
google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 h1:0nDDozoAU19Qb2HwhXadU8OcsiO/09cnTqhUtq2MEOM=
google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA=
google.golang.org/grpc v1.57.0 h1:kfzNeI/klCGD2YPMUlaGNT3pxvYfga7smW3Vth8Zsiw=
Expand Down
3 changes: 3 additions & 0 deletions examples/openapi/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/curioswitch/go-docs-handler/examples/openapi

go 1.19
109 changes: 109 additions & 0 deletions examples/openapi/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package main

import (
_ "embed"
"encoding/json"
"log"
"net/http"
"strconv"
"strings"

docshandler "github.com/curioswitch/go-docs-handler"
"github.com/curioswitch/go-docs-handler/plugins/openapi"
)

//go:embed petstore.yml
var spec []byte

type pet struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Tag string `json:"tag,omitempty"`
}

var nextID = 3

var petstore = map[int]pet{
1: {
ID: "1",
Name: "garfield",
Tag: "cat",
},
2: {
ID: "2",
Name: "snoopy",
Tag: "dog",
},
}

func main() {
docs, err := docshandler.New(openapi.NewPlugin(spec,
openapi.WithExampleRequests("addPet",
pet{
Name: "odie",
Tag: "dog",
}),
))
if err != nil {
log.Fatal(err)
}

mux := http.NewServeMux()

mux.Handle("/pets/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pIDStr := strings.TrimPrefix(r.URL.Path, "/pets/")
if pIDStr == "" {
http.Error(w, "missing pet id", http.StatusBadRequest)
return
}

pID, err := strconv.Atoi(pIDStr)
if err != nil {
http.Error(w, "invalid pet id", http.StatusBadRequest)
return
}
if p, ok := petstore[pID]; ok {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(p); err != nil {
http.Error(w, "failed to encode response", http.StatusInternalServerError)
}
return
} else {
http.Error(w, "pet not found", http.StatusNotFound)
return
}
}))

mux.Handle("/pets", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
var pets []pet
for _, p := range petstore {
pets = append(pets, p)
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(pets); err != nil {
http.Error(w, "failed to encode response", http.StatusInternalServerError)
}
case http.MethodPost:
var p pet
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, "failed to decode request", http.StatusBadRequest)
return
}

petstore[nextID] = p
p.ID = strconv.Itoa(nextID)
nextID++

w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(p); err != nil {
http.Error(w, "failed to encode response", http.StatusInternalServerError)
}
}
}))

mux.Handle("/docs/", http.StripPrefix("/docs", docs))

log.Fatal(http.ListenAndServe(":8080", mux))
}
164 changes: 164 additions & 0 deletions examples/openapi/petstore.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
description: A sample API that uses a petstore as an example to demonstrate features in the OpenAPI 3.0 specification
termsOfService: http://swagger.io/terms/
contact:
name: Swagger API Team
email: apiteam@swagger.io
url: http://swagger.io
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
servers:
- url: https://petstore.swagger.io/v2
paths:
/pets:
get:
description: |
Returns all pets from the system that the user has access to
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
operationId: findPets
parameters:
- name: tags
in: query
description: tags to filter by
required: false
style: form
schema:
$ref: '#/components/schemas/Tags'
- name: limit
in: query
description: maximum number of results to return
required: false
schema:
type: integer
format: int32
responses:
'200':
description: pet response
content:
application/json:
schema:
$ref: '#/components/schemas/Pets'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
description: Creates a new pet in the store. Duplicates are allowed
operationId: addPet
requestBody:
description: Pet to add to the store
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewPet'
responses:
'200':
description: pet response
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/pets/{id}:
get:
description: Returns a user based on a single ID, if the user does not have access to the pet
operationId: find pet by id
parameters:
- name: id
in: path
description: ID of pet to fetch
required: true
schema:
type: integer
format: int64
responses:
'200':
description: pet response
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete:
description: deletes a single pet based on the ID supplied
operationId: deletePet
parameters:
- name: id
in: path
description: ID of pet to delete
required: true
schema:
type: integer
format: int64
responses:
'204':
description: pet deleted
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
Pet:
allOf:
- $ref: '#/components/schemas/NewPet'
- type: object
required:
- id
properties:
id:
type: integer
format: int64

Pets:
type: array
items:
$ref: '#/components/schemas/Pet'

NewPet:
type: object
required:
- name
properties:
name:
type: string
tag:
type: string

Tags:
type: array
items:
type: string

Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
2 changes: 2 additions & 0 deletions go.work
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use (
.
./examples/connect
./examples/grpc
./examples/openapi
./magefiles
./plugins/grpc
./plugins/openapi
./plugins/proto
)

0 comments on commit f0ab668

Please sign in to comment.