This commit is contained in:
Colin Henry 2020-05-20 23:18:58 -07:00
parent 5e8b9a0bf6
commit 6e60671cfd
99 changed files with 13063 additions and 24 deletions

2
.gitignore vendored Normal file → Executable file
View File

@ -1,3 +1,5 @@
cmd/sub-demo/sub-demo
cmd/auth-demo/auth-demo
.vscode/
**/.DS_Store

0
LICENSE Normal file → Executable file
View File

0
README.md Normal file → Executable file
View File

61
arvelie/arvelie.go Executable file
View File

@ -0,0 +1,61 @@
package arvelie
import (
"fmt"
"math"
"strconv"
"strings"
"time"
)
type Arvelie string
func (a *Arvelie) isValid() bool {
if a != nil {
return strings.EqualFold(string(*a), string(FromDate(ToDate(*a))))
}
return false
}
func ToDate(a Arvelie) time.Time {
y := string(a)[0:2]
m := string(a)[2:3]
d, _ := strconv.Atoi(string(a)[3:5])
var mon int
if m == "+" {
mon = 26
} else {
mon = (int(m[0]) - 65)
}
doty := (math.Floor(float64(mon)*14) + math.Floor(float64(d)) - 1)
yr, _ := strconv.Atoi(fmt.Sprintf("20%s", y))
return time.Date(yr, 1, 1, 0, 0, 0, 0, time.UTC).AddDate(0, 0, int(doty))
}
func FromDate(date time.Time) Arvelie {
y := date.Format("06")
doty := date.YearDay()
var m string
if doty == 365 || doty == 366 {
m = "+"
} else {
m = strings.ToUpper(string([]byte{byte(97 + math.Floor(float64(doty/14)))}))
}
var d string
switch doty {
case 365:
d = fmt.Sprintf("%02d", 1)
break
case 366:
d = fmt.Sprintf("%02d", 2)
break
default:
d = fmt.Sprintf("%02d", (doty % 14))
}
return Arvelie(fmt.Sprintf("%s%s%s", y, m, d))
}

53
arvelie/arvelie_test.go Executable file
View File

@ -0,0 +1,53 @@
package arvelie_test
import (
"fmt"
"strings"
"testing"
"time"
"github.com/jchenry/libs/arvelie"
)
func TestFromDate(t *testing.T) {
tests := [][]string{
{"02A01", "2002-01-01"},
{"13B12", "2013-01-26"},
{"24C01", "2024-01-29"},
{"01D07", "2001-02-18"},
{"02E07", "2002-03-04"},
{"03+01", "2003-12-31"},
}
for i := range tests {
dt, _ := time.Parse("2006-01-02", tests[i][1])
a := arvelie.FromDate(dt)
expected := tests[i][0]
if !strings.EqualFold(string(a), expected) {
fmt.Printf("%v != %v\n", expected, a)
t.Fail()
}
}
}
func TestToDate(t *testing.T) {
tests := [][]string{
{"02A01", "2002-01-01"},
{"13B12", "2013-01-26"},
{"24C01", "2024-01-29"},
{"01D07", "2001-02-18"},
{"02E07", "2002-03-04"},
{"03+01", "2003-12-31"},
}
for i := range tests {
d1, _ := time.Parse("2006-01-02", tests[i][1])
dt := arvelie.ToDate(arvelie.Arvelie(tests[i][0]))
if !d1.Equal(dt) {
fmt.Printf("%s != %s\n", d1, dt)
t.Fail()
}
}
}

15
arvelie/doc.go Executable file
View File

@ -0,0 +1,15 @@
package arvelie
// The Arvelie Calendar has 26 months of 14 days each.
// Each month has 2 weeks of 7 days, and each month's name is one of the 26 letters of the alphabet.
// The 365th day of the year is the Year Day(+01), preceded by the Leap Day(+02) on leap years.
//
//Examples:
// 02A01 2002-01-01
// 13B12 2013-01-26
// 24C01 2024-01-29
// 01D07 2001-02-18
// 02E07 2002-03-04
// 03+01 2003-12-31
// Boosted lovingly from https://github.com/XXIIVV/Oscean/blob/master/scripts/lib/arvelie.js

0
auth/auth.go Normal file → Executable file
View File

0
auth/callback.go Normal file → Executable file
View File

0
auth/config.go Normal file → Executable file
View File

0
auth/login.go Normal file → Executable file
View File

0
auth/logout.go Normal file → Executable file
View File

0
auth/middleware.go Normal file → Executable file
View File

0
auth/service.go Normal file → Executable file
View File

0
auth/session.go Normal file → Executable file
View File

0
auth/user.go Normal file → Executable file
View File

0
cmd/auth-demo/home.html Normal file → Executable file
View File

0
cmd/auth-demo/main.go Normal file → Executable file
View File

0
cmd/auth-demo/public/app.css Normal file → Executable file
View File

0
cmd/auth-demo/user.html Normal file → Executable file
View File

13
cmd/now/main.go Executable file
View File

@ -0,0 +1,13 @@
package main
import (
"fmt"
"time"
"github.com/jchenry/libs/neralie"
)
func main() {
a := neralie.FromTime(time.Now())
fmt.Println(a)
}

BIN
cmd/now/now Executable file

Binary file not shown.

24
cmd/openapi-tinkertoy/out/go/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1 @@
5.0.0-SNAPSHOT

View File

@ -0,0 +1,8 @@
language: go
install:
- go get -d -v .
script:
- go build -v ./

View File

@ -0,0 +1,14 @@
FROM golang:1.10 AS build
WORKDIR /go/src
COPY go ./go
COPY main.go .
ENV CGO_ENABLED=0
RUN go get -d -v ./...
RUN go build -a -installsuffix cgo -o openapi .
FROM scratch AS runtime
COPY --from=build /go/src/openapi ./
EXPOSE 8080/tcp
ENTRYPOINT ["./openapi"]

View File

@ -0,0 +1,120 @@
# Go API client for openapi
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.
- API version: 1.0.0
- Package version: 1.0.0
- Build package: org.openapitools.codegen.languages.GoClientCodegen
## Installation
Install the following dependencies:
```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
go get golang.org/x/net/context
go get github.com/antihax/optional
```
Put the package under your project folder and add the following in import:
```golang
import "./openapi"
```
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **Post** /pet | Add a new pet to the store
*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **Delete** /pet/{petId} | Deletes a pet
*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **Get** /pet/findByStatus | Finds Pets by status
*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **Get** /pet/findByTags | Finds Pets by tags
*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **Get** /pet/{petId} | Find pet by ID
*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **Put** /pet | Update an existing pet
*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **Post** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **Post** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **Delete** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **Get** /store/inventory | Returns pet inventories by status
*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **Get** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **Post** /store/order | Place an order for a pet
*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **Post** /user | Create user
*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **Post** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **Post** /user/createWithList | Creates list of users with given input array
*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **Delete** /user/{username} | Delete user
*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **Get** /user/{username} | Get user by user name
*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **Get** /user/login | Logs user into the system
*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **Get** /user/logout | Logs out current logged in user session
*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **Put** /user/{username} | Updated user
## Documentation For Models
- [ApiResponse](docs/ApiResponse.md)
- [Category](docs/Category.md)
- [Order](docs/Order.md)
- [Pet](docs/Pet.md)
- [Tag](docs/Tag.md)
- [User](docs/User.md)
## Documentation For Authorization
## api_key
- **Type**: API key
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAPIKey, sw.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
r, err := client.Service.Operation(auth, args)
```
## petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- **write:pets**: modify pets in your account
- **read:pets**: read your pets
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING")
r, err := client.Service.Operation(auth, args)
```
Or via OAuth2 module to automatically refresh tokens and perform user authentication.
```golang
import "golang.org/x/oauth2"
/* Perform OAuth2 round trip request and obtain a token */
tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token)
auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource)
r, err := client.Service.Operation(auth, args)
```
## Author

View File

@ -0,0 +1,96 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"net/http"
"os"
)
// PetApiRouter defines the required methods for binding the api requests to a responses for the PetApi
// The PetApiRouter implementation should parse necessary information from the http request,
// pass the data to a PetApiServicer to perform the required actions, then write the service results to the http response.
type PetApiRouter interface {
AddPet(http.ResponseWriter, *http.Request)
DeletePet(http.ResponseWriter, *http.Request)
FindPetsByStatus(http.ResponseWriter, *http.Request)
FindPetsByTags(http.ResponseWriter, *http.Request)
GetPetById(http.ResponseWriter, *http.Request)
UpdatePet(http.ResponseWriter, *http.Request)
UpdatePetWithForm(http.ResponseWriter, *http.Request)
UploadFile(http.ResponseWriter, *http.Request)
}
// StoreApiRouter defines the required methods for binding the api requests to a responses for the StoreApi
// The StoreApiRouter implementation should parse necessary information from the http request,
// pass the data to a StoreApiServicer to perform the required actions, then write the service results to the http response.
type StoreApiRouter interface {
DeleteOrder(http.ResponseWriter, *http.Request)
GetInventory(http.ResponseWriter, *http.Request)
GetOrderById(http.ResponseWriter, *http.Request)
PlaceOrder(http.ResponseWriter, *http.Request)
}
// UserApiRouter defines the required methods for binding the api requests to a responses for the UserApi
// The UserApiRouter implementation should parse necessary information from the http request,
// pass the data to a UserApiServicer to perform the required actions, then write the service results to the http response.
type UserApiRouter interface {
CreateUser(http.ResponseWriter, *http.Request)
CreateUsersWithArrayInput(http.ResponseWriter, *http.Request)
CreateUsersWithListInput(http.ResponseWriter, *http.Request)
DeleteUser(http.ResponseWriter, *http.Request)
GetUserByName(http.ResponseWriter, *http.Request)
LoginUser(http.ResponseWriter, *http.Request)
LogoutUser(http.ResponseWriter, *http.Request)
UpdateUser(http.ResponseWriter, *http.Request)
}
// PetApiServicer defines the api actions for the PetApi service
// This interface intended to stay up to date with the openapi yaml used to generate it,
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type PetApiServicer interface {
AddPet(Pet) (interface{}, error)
DeletePet(int64, string) (interface{}, error)
FindPetsByStatus([]string) (interface{}, error)
FindPetsByTags([]string) (interface{}, error)
GetPetById(int64) (interface{}, error)
UpdatePet(Pet) (interface{}, error)
UpdatePetWithForm(int64, string, string) (interface{}, error)
UploadFile(int64, string, *os.File) (interface{}, error)
}
// StoreApiServicer defines the api actions for the StoreApi service
// This interface intended to stay up to date with the openapi yaml used to generate it,
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type StoreApiServicer interface {
DeleteOrder(string) (interface{}, error)
GetInventory() (interface{}, error)
GetOrderById(int64) (interface{}, error)
PlaceOrder(Order) (interface{}, error)
}
// UserApiServicer defines the api actions for the UserApi service
// This interface intended to stay up to date with the openapi yaml used to generate it,
// while the service implementation can ignored with the .openapi-generator-ignore file
// and updated with the logic required for the API.
type UserApiServicer interface {
CreateUser(User) (interface{}, error)
CreateUsersWithArrayInput([]User) (interface{}, error)
CreateUsersWithListInput([]User) (interface{}, error)
DeleteUser(string) (interface{}, error)
GetUserByName(string) (interface{}, error)
LoginUser(string, string) (interface{}, error)
LogoutUser() (interface{}, error)
UpdateUser(string, User) (interface{}, error)
}

View File

@ -0,0 +1,762 @@
openapi: 3.0.1
info:
description: This is a sample server Petstore server. For this sample, you can use
the api key `special-key` to test the authorization filters.
license:
name: Apache-2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
title: OpenAPI Petstore
version: 1.0.0
servers:
- url: http://petstore.swagger.io/v2
tags:
- description: Everything about your Pets
name: pet
- description: Access to Petstore orders
name: store
- description: Operations about user
name: user
paths:
/pet:
post:
operationId: addPet
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
description: Pet object that needs to be added to the store
required: true
responses:
"405":
content: {}
description: Invalid input
security:
- petstore_auth:
- write:pets
- read:pets
summary: Add a new pet to the store
tags:
- pet
x-codegen-request-body-name: body
put:
operationId: updatePet
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
description: Pet object that needs to be added to the store
required: true
responses:
"400":
content: {}
description: Invalid ID supplied
"404":
content: {}
description: Pet not found
"405":
content: {}
description: Validation exception
security:
- petstore_auth:
- write:pets
- read:pets
summary: Update an existing pet
tags:
- pet
x-codegen-request-body-name: body
/pet/findByStatus:
get:
description: Multiple status values can be provided with comma separated strings
operationId: findPetsByStatus
parameters:
- description: Status values that need to be considered for filter
explode: false
in: query
name: status
required: true
schema:
items:
default: available
enum:
- available
- pending
- sold
type: string
type: array
style: form
responses:
"200":
content:
application/xml:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
application/json:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
description: successful operation
"400":
content: {}
description: Invalid status value
security:
- petstore_auth:
- write:pets
- read:pets
summary: Finds Pets by status
tags:
- pet
/pet/findByTags:
get:
deprecated: true
description: Multiple tags can be provided with comma separated strings. Use
tag1, tag2, tag3 for testing.
operationId: findPetsByTags
parameters:
- description: Tags to filter by
explode: false
in: query
name: tags
required: true
schema:
items:
type: string
type: array
style: form
responses:
"200":
content:
application/xml:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
application/json:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
description: successful operation
"400":
content: {}
description: Invalid tag value
security:
- petstore_auth:
- write:pets
- read:pets
summary: Finds Pets by tags
tags:
- pet
/pet/{petId}:
delete:
operationId: deletePet
parameters:
- in: header
name: api_key
schema:
type: string
- description: Pet id to delete
in: path
name: petId
required: true
schema:
format: int64
type: integer
responses:
"400":
content: {}
description: Invalid pet value
security:
- petstore_auth:
- write:pets
- read:pets
summary: Deletes a pet
tags:
- pet
get:
description: Returns a single pet
operationId: getPetById
parameters:
- description: ID of pet to return
in: path
name: petId
required: true
schema:
format: int64
type: integer
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/json:
schema:
$ref: '#/components/schemas/Pet'
description: successful operation
"400":
content: {}
description: Invalid ID supplied
"404":
content: {}
description: Pet not found
security:
- api_key: []
summary: Find pet by ID
tags:
- pet
post:
operationId: updatePetWithForm
parameters:
- description: ID of pet that needs to be updated
in: path
name: petId
required: true
schema:
format: int64
type: integer
requestBody:
content:
application/x-www-form-urlencoded:
schema:
properties:
name:
description: Updated name of the pet
type: string
status:
description: Updated status of the pet
type: string
responses:
"405":
content: {}
description: Invalid input
security:
- petstore_auth:
- write:pets
- read:pets
summary: Updates a pet in the store with form data
tags:
- pet
/pet/{petId}/uploadImage:
post:
operationId: uploadFile
parameters:
- description: ID of pet to update
in: path
name: petId
required: true
schema:
format: int64
type: integer
requestBody:
content:
multipart/form-data:
schema:
properties:
additionalMetadata:
description: Additional data to pass to server
type: string
file:
description: file to upload
format: binary
type: string
responses:
"200":
content:
application/json:
schema:
$ref: '#/components/schemas/ApiResponse'
description: successful operation
security:
- petstore_auth:
- write:pets
- read:pets
summary: uploads an image
tags:
- pet
/store/inventory:
get:
description: Returns a map of status codes to quantities
operationId: getInventory
responses:
"200":
content:
application/json:
schema:
additionalProperties:
format: int32
type: integer
type: object
description: successful operation
security:
- api_key: []
summary: Returns pet inventories by status
tags:
- store
/store/order:
post:
operationId: placeOrder
requestBody:
content:
'*/*':
schema:
$ref: '#/components/schemas/Order'
description: order placed for purchasing the pet
required: true
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
description: successful operation
"400":
content: {}
description: Invalid Order
summary: Place an order for a pet
tags:
- store
x-codegen-request-body-name: body
/store/order/{orderId}:
delete:
description: For valid response try integer IDs with value < 1000. Anything
above 1000 or nonintegers will generate API errors
operationId: deleteOrder
parameters:
- description: ID of the order that needs to be deleted
in: path
name: orderId
required: true
schema:
type: string
responses:
"400":
content: {}
description: Invalid ID supplied
"404":
content: {}
description: Order not found
summary: Delete purchase order by ID
tags:
- store
get:
description: For valid response try integer IDs with value <= 5 or > 10. Other
values will generated exceptions
operationId: getOrderById
parameters:
- description: ID of pet that needs to be fetched
in: path
name: orderId
required: true
schema:
format: int64
maximum: 5
minimum: 1
type: integer
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/Order'
application/json:
schema:
$ref: '#/components/schemas/Order'
description: successful operation
"400":
content: {}
description: Invalid ID supplied
"404":
content: {}
description: Order not found
summary: Find purchase order by ID
tags:
- store
/user:
post:
description: This can only be done by the logged in user.
operationId: createUser
requestBody:
content:
'*/*':
schema:
$ref: '#/components/schemas/User'
description: Created user object
required: true
responses:
default:
content: {}
description: successful operation
summary: Create user
tags:
- user
x-codegen-request-body-name: body
/user/createWithArray:
post:
operationId: createUsersWithArrayInput
requestBody:
content:
'*/*':
schema:
items:
$ref: '#/components/schemas/User'
type: array
description: List of user object
required: true
responses:
default:
content: {}
description: successful operation
summary: Creates list of users with given input array
tags:
- user
x-codegen-request-body-name: body
/user/createWithList:
post:
operationId: createUsersWithListInput
requestBody:
content:
'*/*':
schema:
items:
$ref: '#/components/schemas/User'
type: array
description: List of user object
required: true
responses:
default:
content: {}
description: successful operation
summary: Creates list of users with given input array
tags:
- user
x-codegen-request-body-name: body
/user/login:
get:
operationId: loginUser
parameters:
- description: The user name for login
in: query
name: username
required: true
schema:
type: string
- description: The password for login in clear text
in: query
name: password
required: true
schema:
type: string
responses:
"200":
content:
application/xml:
schema:
type: string
application/json:
schema:
type: string
description: successful operation
headers:
X-Rate-Limit:
description: calls per hour allowed by the user
schema:
format: int32
type: integer
X-Expires-After:
description: date in UTC when toekn expires
schema:
format: date-time
type: string
"400":
content: {}
description: Invalid username/password supplied
summary: Logs user into the system
tags:
- user
/user/logout:
get:
operationId: logoutUser
responses:
default:
content: {}
description: successful operation
summary: Logs out current logged in user session
tags:
- user
/user/{username}:
delete:
description: This can only be done by the logged in user.
operationId: deleteUser
parameters:
- description: The name that needs to be deleted
in: path
name: username
required: true
schema:
type: string
responses:
"400":
content: {}
description: Invalid username supplied
"404":
content: {}
description: User not found
summary: Delete user
tags:
- user
get:
operationId: getUserByName
parameters:
- description: The name that needs to be fetched. Use user1 for testing.
in: path
name: username
required: true
schema:
type: string
responses:
"200":
content:
application/xml:
schema:
$ref: '#/components/schemas/User'
application/json:
schema:
$ref: '#/components/schemas/User'
description: successful operation
"400":
content: {}
description: Invalid username supplied
"404":
content: {}
description: User not found
summary: Get user by user name
tags:
- user
put:
description: This can only be done by the logged in user.
operationId: updateUser
parameters:
- description: name that need to be deleted
in: path
name: username
required: true
schema:
type: string
requestBody:
content:
'*/*':
schema:
$ref: '#/components/schemas/User'
description: Updated user object
required: true
responses:
"400":
content: {}
description: Invalid user supplied
"404":
content: {}
description: User not found
summary: Updated user
tags:
- user
x-codegen-request-body-name: body
components:
schemas:
Order:
description: An order for a pets from the pet store
example:
petId: 6
quantity: 1
id: 0
shipDate: 2000-01-23T04:56:07.000+00:00
complete: false
status: placed
properties:
id:
format: int64
type: integer
petId:
format: int64
type: integer
quantity:
format: int32
type: integer
shipDate:
format: date-time
type: string
status:
description: Order Status
enum:
- placed
- approved
- delivered
type: string
complete:
default: false
type: boolean
title: Pet Order
type: object
xml:
name: Order
Category:
description: A category for a pet
example:
name: name
id: 6
properties:
id:
format: int64
type: integer
name:
type: string
title: Pet category
type: object
xml:
name: Category
User:
description: A User who is purchasing from the pet store
example:
firstName: firstName
lastName: lastName
password: password
userStatus: 6
phone: phone
id: 0
email: email
username: username
properties:
id:
format: int64
type: integer
username:
type: string
firstName:
type: string
lastName:
type: string
email:
type: string
password:
type: string
phone:
type: string
userStatus:
description: User Status
format: int32
type: integer
title: a User
type: object
xml:
name: User
Tag:
description: A tag for a pet
example:
name: name
id: 1
properties:
id:
format: int64
type: integer
name:
type: string
title: Pet Tag
type: object
xml:
name: Tag
Pet:
description: A pet for sale in the pet store
example:
photoUrls:
- photoUrls
- photoUrls
name: doggie
id: 0
category:
name: name
id: 6
tags:
- name: name
id: 1
- name: name
id: 1
status: available
properties:
id:
format: int64
type: integer
category:
$ref: '#/components/schemas/Category'
name:
example: doggie
type: string
photoUrls:
items:
type: string
type: array
xml:
name: photoUrl
wrapped: true
tags:
items:
$ref: '#/components/schemas/Tag'
type: array
xml:
name: tag
wrapped: true
status:
description: pet status in the store
enum:
- available
- pending
- sold
type: string
required:
- name
- photoUrls
title: a Pet
type: object
xml:
name: Pet
ApiResponse:
description: Describes the result of uploading an image resource
example:
code: 0
type: type
message: message
properties:
code:
format: int32
type: integer
type:
type: string
message:
type: string
title: An uploaded response
type: object
securitySchemes:
petstore_auth:
flows:
implicit:
authorizationUrl: http://petstore.swagger.io/api/oauth/dialog
scopes:
write:pets: modify pets in your account
read:pets: read your pets
type: oauth2
api_key:
in: header
name: api_key
type: apiKey

View File

@ -0,0 +1,236 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// A PetApiController binds http requests to an api service and writes the service results to the http response
type PetApiController struct {
service PetApiServicer
}
// NewPetApiController creates a default api controller
func NewPetApiController(s PetApiServicer) Router {
return &PetApiController{ service: s }
}
// Routes returns all of the api route for the PetApiController
func (c *PetApiController) Routes() Routes {
return Routes{
{
"AddPet",
strings.ToUpper("Post"),
"/v2/pet",
c.AddPet,
},
{
"DeletePet",
strings.ToUpper("Delete"),
"/v2/pet/{petId}",
c.DeletePet,
},
{
"FindPetsByStatus",
strings.ToUpper("Get"),
"/v2/pet/findByStatus",
c.FindPetsByStatus,
},
{
"FindPetsByTags",
strings.ToUpper("Get"),
"/v2/pet/findByTags",
c.FindPetsByTags,
},
{
"GetPetById",
strings.ToUpper("Get"),
"/v2/pet/{petId}",
c.GetPetById,
},
{
"UpdatePet",
strings.ToUpper("Put"),
"/v2/pet",
c.UpdatePet,
},
{
"UpdatePetWithForm",
strings.ToUpper("Post"),
"/v2/pet/{petId}",
c.UpdatePetWithForm,
},
{
"UploadFile",
strings.ToUpper("Post"),
"/v2/pet/{petId}/uploadImage",
c.UploadFile,
},
}
}
// AddPet - Add a new pet to the store
func (c *PetApiController) AddPet(w http.ResponseWriter, r *http.Request) {
body := &Pet{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.AddPet(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// DeletePet - Deletes a pet
func (c *PetApiController) DeletePet(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
apiKey := r.Header.Get("apiKey")
result, err := c.service.DeletePet(petId, apiKey)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FindPetsByStatus - Finds Pets by status
func (c *PetApiController) FindPetsByStatus(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
status := strings.Split(query.Get("status"), ",")
result, err := c.service.FindPetsByStatus(status)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// FindPetsByTags - Finds Pets by tags
func (c *PetApiController) FindPetsByTags(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
tags := strings.Split(query.Get("tags"), ",")
result, err := c.service.FindPetsByTags(tags)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetPetById - Find pet by ID
func (c *PetApiController) GetPetById(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.GetPetById(petId)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UpdatePet - Update an existing pet
func (c *PetApiController) UpdatePet(w http.ResponseWriter, r *http.Request) {
body := &Pet{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.UpdatePet(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UpdatePetWithForm - Updates a pet in the store with form data
func (c *PetApiController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
name := r.FormValue("name")
status := r.FormValue("status")
result, err := c.service.UpdatePetWithForm(petId, name, status)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UploadFile - uploads an image
func (c *PetApiController) UploadFile(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(500)
return
}
params := mux.Vars(r)
petId, err := parseIntParameter(params["petId"])
if err != nil {
w.WriteHeader(500)
return
}
additionalMetadata := r.FormValue("additionalMetadata")
file, err := ReadFormFileToTempFile(r, "file")
if err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.UploadFile(petId, additionalMetadata, file)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -0,0 +1,82 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"errors"
"os"
)
// PetApiService is a service that implents the logic for the PetApiServicer
// This service should implement the business logic for every endpoint for the PetApi API.
// Include any external packages or services that will be required by this service.
type PetApiService struct {
}
// NewPetApiService creates a default api service
func NewPetApiService() PetApiServicer {
return &PetApiService{}
}
// AddPet - Add a new pet to the store
func (s *PetApiService) AddPet(body Pet) (interface{}, error) {
// TODO - update AddPet with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'AddPet' not implemented")
}
// DeletePet - Deletes a pet
func (s *PetApiService) DeletePet(petId int64, apiKey string) (interface{}, error) {
// TODO - update DeletePet with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'DeletePet' not implemented")
}
// FindPetsByStatus - Finds Pets by status
func (s *PetApiService) FindPetsByStatus(status []string) (interface{}, error) {
// TODO - update FindPetsByStatus with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'FindPetsByStatus' not implemented")
}
// FindPetsByTags - Finds Pets by tags
func (s *PetApiService) FindPetsByTags(tags []string) (interface{}, error) {
// TODO - update FindPetsByTags with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'FindPetsByTags' not implemented")
}
// GetPetById - Find pet by ID
func (s *PetApiService) GetPetById(petId int64) (interface{}, error) {
// TODO - update GetPetById with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'GetPetById' not implemented")
}
// UpdatePet - Update an existing pet
func (s *PetApiService) UpdatePet(body Pet) (interface{}, error) {
// TODO - update UpdatePet with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'UpdatePet' not implemented")
}
// UpdatePetWithForm - Updates a pet in the store with form data
func (s *PetApiService) UpdatePetWithForm(petId int64, name string, status string) (interface{}, error) {
// TODO - update UpdatePetWithForm with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'UpdatePetWithForm' not implemented")
}
// UploadFile - uploads an image
func (s *PetApiService) UploadFile(petId int64, additionalMetadata string, file *os.File) (interface{}, error) {
// TODO - update UploadFile with the required logic for this service method.
// Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'UploadFile' not implemented")
}

View File

@ -0,0 +1,117 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// A StoreApiController binds http requests to an api service and writes the service results to the http response
type StoreApiController struct {
service StoreApiServicer
}
// NewStoreApiController creates a default api controller
func NewStoreApiController(s StoreApiServicer) Router {
return &StoreApiController{ service: s }
}
// Routes returns all of the api route for the StoreApiController
func (c *StoreApiController) Routes() Routes {
return Routes{
{
"DeleteOrder",
strings.ToUpper("Delete"),
"/v2/store/order/{orderId}",
c.DeleteOrder,
},
{
"GetInventory",
strings.ToUpper("Get"),
"/v2/store/inventory",
c.GetInventory,
},
{
"GetOrderById",
strings.ToUpper("Get"),
"/v2/store/order/{orderId}",
c.GetOrderById,
},
{
"PlaceOrder",
strings.ToUpper("Post"),
"/v2/store/order",
c.PlaceOrder,
},
}
}
// DeleteOrder - Delete purchase order by ID
func (c *StoreApiController) DeleteOrder(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
orderId := params["orderId"]
result, err := c.service.DeleteOrder(orderId)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetInventory - Returns pet inventories by status
func (c *StoreApiController) GetInventory(w http.ResponseWriter, r *http.Request) {
result, err := c.service.GetInventory()
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetOrderById - Find purchase order by ID
func (c *StoreApiController) GetOrderById(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
orderId, err := parseIntParameter(params["orderId"])
if err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.GetOrderById(orderId)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// PlaceOrder - Place an order for a pet
func (c *StoreApiController) PlaceOrder(w http.ResponseWriter, r *http.Request) {
body := &Order{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.PlaceOrder(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -0,0 +1,53 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"errors"
)
// StoreApiService is a service that implents the logic for the StoreApiServicer
// This service should implement the business logic for every endpoint for the StoreApi API.
// Include any external packages or services that will be required by this service.
type StoreApiService struct {
}
// NewStoreApiService creates a default api service
func NewStoreApiService() StoreApiServicer {
return &StoreApiService{}
}
// DeleteOrder - Delete purchase order by ID
func (s *StoreApiService) DeleteOrder(orderId string) (interface{}, error) {
// TODO - update DeleteOrder with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'DeleteOrder' not implemented")
}
// GetInventory - Returns pet inventories by status
func (s *StoreApiService) GetInventory() (interface{}, error) {
// TODO - update GetInventory with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'GetInventory' not implemented")
}
// GetOrderById - Find purchase order by ID
func (s *StoreApiService) GetOrderById(orderId int64) (interface{}, error) {
// TODO - update GetOrderById with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'GetOrderById' not implemented")
}
// PlaceOrder - Place an order for a pet
func (s *StoreApiService) PlaceOrder(body Order) (interface{}, error) {
// TODO - update PlaceOrder with the required logic for this service method.
// Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'PlaceOrder' not implemented")
}

View File

@ -0,0 +1,203 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"encoding/json"
"net/http"
"strings"
"github.com/gorilla/mux"
)
// A UserApiController binds http requests to an api service and writes the service results to the http response
type UserApiController struct {
service UserApiServicer
}
// NewUserApiController creates a default api controller
func NewUserApiController(s UserApiServicer) Router {
return &UserApiController{ service: s }
}
// Routes returns all of the api route for the UserApiController
func (c *UserApiController) Routes() Routes {
return Routes{
{
"CreateUser",
strings.ToUpper("Post"),
"/v2/user",
c.CreateUser,
},
{
"CreateUsersWithArrayInput",
strings.ToUpper("Post"),
"/v2/user/createWithArray",
c.CreateUsersWithArrayInput,
},
{
"CreateUsersWithListInput",
strings.ToUpper("Post"),
"/v2/user/createWithList",
c.CreateUsersWithListInput,
},
{
"DeleteUser",
strings.ToUpper("Delete"),
"/v2/user/{username}",
c.DeleteUser,
},
{
"GetUserByName",
strings.ToUpper("Get"),
"/v2/user/{username}",
c.GetUserByName,
},
{
"LoginUser",
strings.ToUpper("Get"),
"/v2/user/login",
c.LoginUser,
},
{
"LogoutUser",
strings.ToUpper("Get"),
"/v2/user/logout",
c.LogoutUser,
},
{
"UpdateUser",
strings.ToUpper("Put"),
"/v2/user/{username}",
c.UpdateUser,
},
}
}
// CreateUser - Create user
func (c *UserApiController) CreateUser(w http.ResponseWriter, r *http.Request) {
body := &User{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.CreateUser(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// CreateUsersWithArrayInput - Creates list of users with given input array
func (c *UserApiController) CreateUsersWithArrayInput(w http.ResponseWriter, r *http.Request) {
body := &[]User{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.CreateUsersWithArrayInput(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// CreateUsersWithListInput - Creates list of users with given input array
func (c *UserApiController) CreateUsersWithListInput(w http.ResponseWriter, r *http.Request) {
body := &[]User{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.CreateUsersWithListInput(*body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// DeleteUser - Delete user
func (c *UserApiController) DeleteUser(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
username := params["username"]
result, err := c.service.DeleteUser(username)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// GetUserByName - Get user by user name
func (c *UserApiController) GetUserByName(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
username := params["username"]
result, err := c.service.GetUserByName(username)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// LoginUser - Logs user into the system
func (c *UserApiController) LoginUser(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
username := query.Get("username")
password := query.Get("password")
result, err := c.service.LoginUser(username, password)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// LogoutUser - Logs out current logged in user session
func (c *UserApiController) LogoutUser(w http.ResponseWriter, r *http.Request) {
result, err := c.service.LogoutUser()
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}
// UpdateUser - Updated user
func (c *UserApiController) UpdateUser(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
username := params["username"]
body := &User{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(500)
return
}
result, err := c.service.UpdateUser(username, *body)
if err != nil {
w.WriteHeader(500)
return
}
EncodeJSONResponse(result, nil, w)
}

View File

@ -0,0 +1,81 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"errors"
)
// UserApiService is a service that implents the logic for the UserApiServicer
// This service should implement the business logic for every endpoint for the UserApi API.
// Include any external packages or services that will be required by this service.
type UserApiService struct {
}
// NewUserApiService creates a default api service
func NewUserApiService() UserApiServicer {
return &UserApiService{}
}
// CreateUser - Create user
func (s *UserApiService) CreateUser(body User) (interface{}, error) {
// TODO - update CreateUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'CreateUser' not implemented")
}
// CreateUsersWithArrayInput - Creates list of users with given input array
func (s *UserApiService) CreateUsersWithArrayInput(body []User) (interface{}, error) {
// TODO - update CreateUsersWithArrayInput with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'CreateUsersWithArrayInput' not implemented")
}
// CreateUsersWithListInput - Creates list of users with given input array
func (s *UserApiService) CreateUsersWithListInput(body []User) (interface{}, error) {
// TODO - update CreateUsersWithListInput with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'CreateUsersWithListInput' not implemented")
}
// DeleteUser - Delete user
func (s *UserApiService) DeleteUser(username string) (interface{}, error) {
// TODO - update DeleteUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'DeleteUser' not implemented")
}
// GetUserByName - Get user by user name
func (s *UserApiService) GetUserByName(username string) (interface{}, error) {
// TODO - update GetUserByName with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'GetUserByName' not implemented")
}
// LoginUser - Logs user into the system
func (s *UserApiService) LoginUser(username string, password string) (interface{}, error) {
// TODO - update LoginUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'LoginUser' not implemented")
}
// LogoutUser - Logs out current logged in user session
func (s *UserApiService) LogoutUser() (interface{}, error) {
// TODO - update LogoutUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'LogoutUser' not implemented")
}
// UpdateUser - Updated user
func (s *UserApiService) UpdateUser(username string, body User) (interface{}, error) {
// TODO - update UpdateUser with the required logic for this service method.
// Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation.
return nil, errors.New("service method 'UpdateUser' not implemented")
}

View File

@ -0,0 +1,548 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"golang.org/x/oauth2"
)
var (
jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`)
xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`)
)
// APIClient manages communication with the OpenAPI Petstore API v1.0.0
// In most cases there should be only one, shared, APIClient.
type APIClient struct {
cfg *Configuration
common service // Reuse a single struct instead of allocating one for each service on the heap.
// API Services
PetApi *PetApiService
StoreApi *StoreApiService
UserApi *UserApiService
}
type service struct {
client *APIClient
}
// NewAPIClient creates a new API client. Requires a userAgent string describing your application.
// optionally a custom http.Client to allow for advanced features such as caching.
func NewAPIClient(cfg *Configuration) *APIClient {
if cfg.HTTPClient == nil {
cfg.HTTPClient = http.DefaultClient
}
c := &APIClient{}
c.cfg = cfg
c.common.client = c
// API Services
c.PetApi = (*PetApiService)(&c.common)
c.StoreApi = (*StoreApiService)(&c.common)
c.UserApi = (*UserApiService)(&c.common)
return c
}
func atoi(in string) (int, error) {
return strconv.Atoi(in)
}
// selectHeaderContentType select a content type from the available list.
func selectHeaderContentType(contentTypes []string) string {
if len(contentTypes) == 0 {
return ""
}
if contains(contentTypes, "application/json") {
return "application/json"
}
return contentTypes[0] // use the first content type specified in 'consumes'
}
// selectHeaderAccept join all accept types and return
func selectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
// contains is a case insenstive match, finding needle in a haystack
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.ToLower(a) == strings.ToLower(needle) {
return true
}
}
return false
}
// Verify optional parameters are of the correct type.
func typeCheckParameter(obj interface{}, expected string, name string) error {
// Make sure there is an object.
if obj == nil {
return nil
}
// Check the type is as expected.
if reflect.TypeOf(obj).String() != expected {
return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String())
}
return nil
}
// parameterToString convert interface{} parameters to string, using a delimiter if format is provided.
func parameterToString(obj interface{}, collectionFormat string) string {
var delimiter string
switch collectionFormat {
case "pipes":
delimiter = "|"
case "ssv":
delimiter = " "
case "tsv":
delimiter = "\t"
case "csv":
delimiter = ","
}
if reflect.TypeOf(obj).Kind() == reflect.Slice {
return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
} else if t, ok := obj.(time.Time); ok {
return t.Format(time.RFC3339)
}
return fmt.Sprintf("%v", obj)
}
// helper for converting interface{} parameters to json strings
func parameterToJson(obj interface{}) (string, error) {
jsonBuf, err := json.Marshal(obj)
if err != nil {
return "", err
}
return string(jsonBuf), err
}
// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
if c.cfg.Debug {
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, err
}
log.Printf("\n%s\n", string(dump))
}
resp, err := c.cfg.HTTPClient.Do(request)
if err != nil {
return resp, err
}
if c.cfg.Debug {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return resp, err
}
log.Printf("\n%s\n", string(dump))
}
return resp, err
}
// ChangeBasePath changes base path to allow switching to mocks
func (c *APIClient) ChangeBasePath(path string) {
c.cfg.BasePath = path
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {
return c.cfg
}
// prepareRequest build the request
func (c *APIClient) prepareRequest(
ctx context.Context,
path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams url.Values,
formFileName string,
fileName string,
fileBytes []byte) (localVarRequest *http.Request, err error) {
var body *bytes.Buffer
// Detect postBody type and post.
if postBody != nil {
contentType := headerParams["Content-Type"]
if contentType == "" {
contentType = detectContentType(postBody)
headerParams["Content-Type"] = contentType
}
body, err = setBody(postBody, contentType)
if err != nil {
return nil, err
}
}
// add form parameters and file if available.
if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") {
if body != nil {
return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
}
body = &bytes.Buffer{}
w := multipart.NewWriter(body)
for k, v := range formParams {
for _, iv := range v {
if strings.HasPrefix(k, "@") { // file
err = addFile(w, k[1:], iv)
if err != nil {
return nil, err
}
} else { // form value
w.WriteField(k, iv)
}
}
}
if len(fileBytes) > 0 && fileName != "" {
w.Boundary()
//_, fileNm := filepath.Split(fileName)
part, err := w.CreateFormFile(formFileName, filepath.Base(fileName))
if err != nil {
return nil, err
}
_, err = part.Write(fileBytes)
if err != nil {
return nil, err
}
}
// Set the Boundary in the Content-Type
headerParams["Content-Type"] = w.FormDataContentType()
// Set Content-Length
headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
w.Close()
}
if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 {
if body != nil {
return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.")
}
body = &bytes.Buffer{}
body.WriteString(formParams.Encode())
// Set Content-Length
headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
}
// Setup path and query parameters
url, err := url.Parse(path)
if err != nil {
return nil, err
}
// Override request host, if applicable
if c.cfg.Host != "" {
url.Host = c.cfg.Host
}
// Override request scheme, if applicable
if c.cfg.Scheme != "" {
url.Scheme = c.cfg.Scheme
}
// Adding Query Param
query := url.Query()
for k, v := range queryParams {
for _, iv := range v {
query.Add(k, iv)
}
}
// Encode the parameters.
url.RawQuery = query.Encode()
// Generate a new request
if body != nil {
localVarRequest, err = http.NewRequest(method, url.String(), body)
} else {
localVarRequest, err = http.NewRequest(method, url.String(), nil)
}
if err != nil {
return nil, err
}
// add header parameters, if any
if len(headerParams) > 0 {
headers := http.Header{}
for h, v := range headerParams {
headers.Set(h, v)
}
localVarRequest.Header = headers
}
// Add the user agent to the request.
localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent)
if ctx != nil {
// add context to the request
localVarRequest = localVarRequest.WithContext(ctx)
// Walk through any authentication.
// OAuth2 authentication
if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
// We were able to grab an oauth2 token from the context
var latestToken *oauth2.Token
if latestToken, err = tok.Token(); err != nil {
return nil, err
}
latestToken.SetAuthHeader(localVarRequest)
}
// Basic HTTP Authentication
if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
}
// AccessToken Authentication
if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
localVarRequest.Header.Add("Authorization", "Bearer "+auth)
}
}
for header, value := range c.cfg.DefaultHeader {
localVarRequest.Header.Add(header, value)
}
return localVarRequest, nil
}
func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
if len(b) == 0 {
return nil
}
if s, ok := v.(*string); ok {
*s = string(b)
return nil
}
if f, ok := v.(**os.File); ok {
*f, err = ioutil.TempFile("", "HttpClientFile")
if err != nil {
return
}
_, err = (*f).Write(b)
_, err = (*f).Seek(0, io.SeekStart)
return
}
if xmlCheck.MatchString(contentType) {
if err = xml.Unmarshal(b, v); err != nil {
return err
}
return nil
}
if jsonCheck.MatchString(contentType) {
if err = json.Unmarshal(b, v); err != nil {
return err
}
return nil
}
return errors.New("undefined response type")
}
// Add a file to the multipart request
func addFile(w *multipart.Writer, fieldName, path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
part, err := w.CreateFormFile(fieldName, filepath.Base(path))
if err != nil {
return err
}
_, err = io.Copy(part, file)
return err
}
// Prevent trying to import "fmt"
func reportError(format string, a ...interface{}) error {
return fmt.Errorf(format, a...)
}
// Set request body from an interface{}
func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
if bodyBuf == nil {
bodyBuf = &bytes.Buffer{}
}
if reader, ok := body.(io.Reader); ok {
_, err = bodyBuf.ReadFrom(reader)
} else if b, ok := body.([]byte); ok {
_, err = bodyBuf.Write(b)
} else if s, ok := body.(string); ok {
_, err = bodyBuf.WriteString(s)
} else if s, ok := body.(*string); ok {
_, err = bodyBuf.WriteString(*s)
} else if jsonCheck.MatchString(contentType) {
err = json.NewEncoder(bodyBuf).Encode(body)
} else if xmlCheck.MatchString(contentType) {
err = xml.NewEncoder(bodyBuf).Encode(body)
}
if err != nil {
return nil, err
}
if bodyBuf.Len() == 0 {
err = fmt.Errorf("Invalid body type %s\n", contentType)
return nil, err
}
return bodyBuf, nil
}
// detectContentType method is used to figure out `Request.Body` content type for request header
func detectContentType(body interface{}) string {
contentType := "text/plain; charset=utf-8"
kind := reflect.TypeOf(body).Kind()
switch kind {
case reflect.Struct, reflect.Map, reflect.Ptr:
contentType = "application/json; charset=utf-8"
case reflect.String:
contentType = "text/plain; charset=utf-8"
default:
if b, ok := body.([]byte); ok {
contentType = http.DetectContentType(b)
} else if kind == reflect.Slice {
contentType = "application/json; charset=utf-8"
}
}
return contentType
}
// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go
type cacheControl map[string]string
func parseCacheControl(headers http.Header) cacheControl {
cc := cacheControl{}
ccHeader := headers.Get("Cache-Control")
for _, part := range strings.Split(ccHeader, ",") {
part = strings.Trim(part, " ")
if part == "" {
continue
}
if strings.ContainsRune(part, '=') {
keyval := strings.Split(part, "=")
cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
} else {
cc[part] = ""
}
}
return cc
}
// CacheExpires helper function to determine remaining time before repeating a request.
func CacheExpires(r *http.Response) time.Time {
// Figure out when the cache expires.
var expires time.Time
now, err := time.Parse(time.RFC1123, r.Header.Get("date"))
if err != nil {
return time.Now()
}
respCacheControl := parseCacheControl(r.Header)
if maxAge, ok := respCacheControl["max-age"]; ok {
lifetime, err := time.ParseDuration(maxAge + "s")
if err != nil {
expires = now
} else {
expires = now.Add(lifetime)
}
} else {
expiresHeader := r.Header.Get("Expires")
if expiresHeader != "" {
expires, err = time.Parse(time.RFC1123, expiresHeader)
if err != nil {
expires = now
}
}
}
return expires
}
func strlen(s string) int {
return utf8.RuneCountInString(s)
}
// GenericOpenAPIError Provides access to the body, error and model on returned errors.
type GenericOpenAPIError struct {
body []byte
error string
model interface{}
}
// Error returns non-empty string if there was an error.
func (e GenericOpenAPIError) Error() string {
return e.error
}
// Body returns the raw bytes of the response
func (e GenericOpenAPIError) Body() []byte {
return e.body
}
// Model returns the unpacked model of the error
func (e GenericOpenAPIError) Model() interface{} {
return e.model
}

View File

@ -0,0 +1,130 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"fmt"
"net/http"
"strings"
)
// contextKeys are used to identify the type of value in the context.
// Since these are string, it is possible to get a short description of the
// context key for logging and debugging using key.String().
type contextKey string
func (c contextKey) String() string {
return "auth " + string(c)
}
var (
// ContextOAuth2 takes an oauth2.TokenSource as authentication for the request.
ContextOAuth2 = contextKey("token")
// ContextBasicAuth takes BasicAuth as authentication for the request.
ContextBasicAuth = contextKey("basic")
// ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken")
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
type BasicAuth struct {
UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
}
// APIKey provides API key based authentication to a request passed via context using ContextAPIKey
type APIKey struct {
Key string
Prefix string
}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string
DefaultValue string
EnumValues []string
}
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
Url string
Description string
Variables map[string]ServerVariable
}
// Configuration stores the configuration of the API client
type Configuration struct {
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Servers []ServerConfiguration
HTTPClient *http.Client
}
// NewConfiguration returns a new Configuration object
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://petstore.swagger.io/v2",
DefaultHeader: make(map[string]string),
UserAgent: "OpenAPI-Generator/1.0.0/go",
Debug: false,
Servers: []ServerConfiguration{
{
Url: "http://petstore.swagger.io/v2",
Description: "No description provided",
},
},
}
return cfg
}
// AddDefaultHeader adds a new HTTP header to the default header in the request
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// ServerUrl returns URL based on server settings
func (c *Configuration) ServerUrl(index int, variables map[string]string) (string, error) {
if index < 0 || len(c.Servers) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(c.Servers) - 1)
}
server := c.Servers[index]
url := server.Url
// go through variables and replace placeholders
for name, variable := range server.Variables {
if value, ok := variables[name]; ok {
found := bool(len(variable.EnumValues) == 0)
for _, enumValue := range variable.EnumValues {
if value == enumValue {
found = true
}
}
if !found {
return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues)
}
url = strings.Replace(url, "{"+name+"}", value, -1)
} else {
url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1)
}
}
return url, nil
}

View File

@ -0,0 +1,13 @@
# ApiResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Code** | **int32** | | [optional]
**Type** | **string** | | [optional]
**Message** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,12 @@
# Category
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **int64** | | [optional]
**Name** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,16 @@
# Order
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **int64** | | [optional]
**PetId** | **int64** | | [optional]
**Quantity** | **int32** | | [optional]
**ShipDate** | [**time.Time**](time.Time.md) | | [optional]
**Status** | **string** | Order Status | [optional]
**Complete** | **bool** | | [optional] [default to false]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,16 @@
# Pet
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **int64** | | [optional]
**Category** | [**Category**](Category.md) | | [optional]
**Name** | **string** | |
**PhotoUrls** | **[]string** | |
**Tags** | [**[]Tag**](Tag.md) | | [optional]
**Status** | **string** | pet status in the store | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,313 @@
# \PetApi
All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**AddPet**](PetApi.md#AddPet) | **Post** /pet | Add a new pet to the store
[**DeletePet**](PetApi.md#DeletePet) | **Delete** /pet/{petId} | Deletes a pet
[**FindPetsByStatus**](PetApi.md#FindPetsByStatus) | **Get** /pet/findByStatus | Finds Pets by status
[**FindPetsByTags**](PetApi.md#FindPetsByTags) | **Get** /pet/findByTags | Finds Pets by tags
[**GetPetById**](PetApi.md#GetPetById) | **Get** /pet/{petId} | Find pet by ID
[**UpdatePet**](PetApi.md#UpdatePet) | **Put** /pet | Update an existing pet
[**UpdatePetWithForm**](PetApi.md#UpdatePetWithForm) | **Post** /pet/{petId} | Updates a pet in the store with form data
[**UploadFile**](PetApi.md#UploadFile) | **Post** /pet/{petId}/uploadImage | uploads an image
## AddPet
> AddPet(ctx, body)
Add a new pet to the store
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
(empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## DeletePet
> DeletePet(ctx, petId, optional)
Deletes a pet
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**petId** | **int64**| Pet id to delete |
**optional** | ***DeletePetOpts** | optional parameters | nil if no parameters
### Optional Parameters
Optional parameters are passed through a pointer to a DeletePetOpts struct
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**apiKey** | **optional.String**| |
### Return type
(empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## FindPetsByStatus
> []Pet FindPetsByStatus(ctx, status)
Finds Pets by status
Multiple status values can be provided with comma separated strings
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**status** | [**[]string**](string.md)| Status values that need to be considered for filter |
### Return type
[**[]Pet**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## FindPetsByTags
> []Pet FindPetsByTags(ctx, tags)
Finds Pets by tags
Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**tags** | [**[]string**](string.md)| Tags to filter by |
### Return type
[**[]Pet**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## GetPetById
> Pet GetPetById(ctx, petId)
Find pet by ID
Returns a single pet
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**petId** | **int64**| ID of pet to return |
### Return type
[**Pet**](Pet.md)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## UpdatePet
> UpdatePet(ctx, body)
Update an existing pet
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
(empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## UpdatePetWithForm
> UpdatePetWithForm(ctx, petId, optional)
Updates a pet in the store with form data
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**petId** | **int64**| ID of pet that needs to be updated |
**optional** | ***UpdatePetWithFormOpts** | optional parameters | nil if no parameters
### Optional Parameters
Optional parameters are passed through a pointer to a UpdatePetWithFormOpts struct
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**name** | **optional.String**| Updated name of the pet |
**status** | **optional.String**| Updated status of the pet |
### Return type
(empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## UploadFile
> ApiResponse UploadFile(ctx, petId, optional)
uploads an image
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**petId** | **int64**| ID of pet to update |
**optional** | ***UploadFileOpts** | optional parameters | nil if no parameters
### Optional Parameters
Optional parameters are passed through a pointer to a UploadFileOpts struct
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**additionalMetadata** | **optional.String**| Additional data to pass to server |
**file** | **optional.Interface of *os.File****optional.*os.File**| file to upload |
### Return type
[**ApiResponse**](ApiResponse.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

View File

@ -0,0 +1,142 @@
# \StoreApi
All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**DeleteOrder**](StoreApi.md#DeleteOrder) | **Delete** /store/order/{orderId} | Delete purchase order by ID
[**GetInventory**](StoreApi.md#GetInventory) | **Get** /store/inventory | Returns pet inventories by status
[**GetOrderById**](StoreApi.md#GetOrderById) | **Get** /store/order/{orderId} | Find purchase order by ID
[**PlaceOrder**](StoreApi.md#PlaceOrder) | **Post** /store/order | Place an order for a pet
## DeleteOrder
> DeleteOrder(ctx, orderId)
Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**orderId** | **string**| ID of the order that needs to be deleted |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## GetInventory
> map[string]int32 GetInventory(ctx, )
Returns pet inventories by status
Returns a map of status codes to quantities
### Required Parameters
This endpoint does not need any parameter.
### Return type
**map[string]int32**
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## GetOrderById
> Order GetOrderById(ctx, orderId)
Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**orderId** | **int64**| ID of pet that needs to be fetched |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## PlaceOrder
> Order PlaceOrder(ctx, body)
Place an order for a pet
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**body** | [**Order**](Order.md)| order placed for purchasing the pet |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

View File

@ -0,0 +1,12 @@
# Tag
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **int64** | | [optional]
**Name** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,18 @@
# User
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Id** | **int64** | | [optional]
**Username** | **string** | | [optional]
**FirstName** | **string** | | [optional]
**LastName** | **string** | | [optional]
**Email** | **string** | | [optional]
**Password** | **string** | | [optional]
**Phone** | **string** | | [optional]
**UserStatus** | **int32** | User Status | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,276 @@
# \UserApi
All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**CreateUser**](UserApi.md#CreateUser) | **Post** /user | Create user
[**CreateUsersWithArrayInput**](UserApi.md#CreateUsersWithArrayInput) | **Post** /user/createWithArray | Creates list of users with given input array
[**CreateUsersWithListInput**](UserApi.md#CreateUsersWithListInput) | **Post** /user/createWithList | Creates list of users with given input array
[**DeleteUser**](UserApi.md#DeleteUser) | **Delete** /user/{username} | Delete user
[**GetUserByName**](UserApi.md#GetUserByName) | **Get** /user/{username} | Get user by user name
[**LoginUser**](UserApi.md#LoginUser) | **Get** /user/login | Logs user into the system
[**LogoutUser**](UserApi.md#LogoutUser) | **Get** /user/logout | Logs out current logged in user session
[**UpdateUser**](UserApi.md#UpdateUser) | **Put** /user/{username} | Updated user
## CreateUser
> CreateUser(ctx, body)
Create user
This can only be done by the logged in user.
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**body** | [**User**](User.md)| Created user object |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## CreateUsersWithArrayInput
> CreateUsersWithArrayInput(ctx, body)
Creates list of users with given input array
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**body** | [**[]User**](User.md)| List of user object |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## CreateUsersWithListInput
> CreateUsersWithListInput(ctx, body)
Creates list of users with given input array
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**body** | [**[]User**](User.md)| List of user object |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## DeleteUser
> DeleteUser(ctx, username)
Delete user
This can only be done by the logged in user.
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**username** | **string**| The name that needs to be deleted |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## GetUserByName
> User GetUserByName(ctx, username)
Get user by user name
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**username** | **string**| The name that needs to be fetched. Use user1 for testing. |
### Return type
[**User**](User.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## LoginUser
> string LoginUser(ctx, username, password)
Logs user into the system
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**username** | **string**| The user name for login |
**password** | **string**| The password for login in clear text |
### Return type
**string**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/xml, application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## LogoutUser
> LogoutUser(ctx, )
Logs out current logged in user session
### Required Parameters
This endpoint does not need any parameter.
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)
## UpdateUser
> UpdateUser(ctx, username, body)
Updated user
This can only be done by the logged in user.
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**username** | **string**| name that need to be deleted |
**body** | [**User**](User.md)| Updated user object |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

View File

@ -0,0 +1,58 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,7 @@
module github.com/GIT_USER_ID/GIT_REPO_ID
require (
github.com/antihax/optional v1.0.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
)

View File

@ -0,0 +1,17 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/aws/aws-sdk-go v1.26.3 h1:szQdfJcUBAhQT0zZEx4sxoDuWb7iScoucxCiVxDmaBk=
github.com/aws/aws-sdk-go v1.26.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=

View File

@ -0,0 +1,32 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"log"
"net/http"
"time"
)
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s %s %s %s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}

View File

@ -0,0 +1,34 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package main
import (
"log"
"net/http"
openapi "github.com/GIT_USER_ID/GIT_REPO_ID/go"
)
func main() {
log.Printf("Server started")
PetApiService := openapi.NewPetApiService()
PetApiController := openapi.NewPetApiController(PetApiService)
StoreApiService := openapi.NewStoreApiService()
StoreApiController := openapi.NewStoreApiController(StoreApiService)
UserApiService := openapi.NewUserApiService()
UserApiController := openapi.NewUserApiController(UserApiService)
router := openapi.NewRouter(PetApiController, StoreApiController, UserApiController)
log.Fatal(http.ListenAndServe(":8080", router))
}

View File

@ -0,0 +1,20 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
// ApiResponse - Describes the result of uploading an image resource
type ApiResponse struct {
Code int32 `json:"code,omitempty"`
Type string `json:"type,omitempty"`
Message string `json:"message,omitempty"`
}

View File

@ -0,0 +1,18 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
// Category - A category for a pet
type Category struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}

View File

@ -0,0 +1,31 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"time"
)
// Order - An order for a pets from the pet store
type Order struct {
Id int64 `json:"id,omitempty"`
PetId int64 `json:"petId,omitempty"`
Quantity int32 `json:"quantity,omitempty"`
ShipDate time.Time `json:"shipDate,omitempty"`
// Order Status
Status string `json:"status,omitempty"`
Complete bool `json:"complete,omitempty"`
}

View File

@ -0,0 +1,27 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
// Pet - A pet for sale in the pet store
type Pet struct {
Id int64 `json:"id,omitempty"`
Category Category `json:"category,omitempty"`
Name string `json:"name"`
PhotoUrls []string `json:"photoUrls"`
Tags []Tag `json:"tags,omitempty"`
// pet status in the store
Status string `json:"status,omitempty"`
}

View File

@ -0,0 +1,18 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
// Tag - A tag for a pet
type Tag struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}

View File

@ -0,0 +1,31 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
// User - A User who is purchasing from the pet store
type User struct {
Id int64 `json:"id,omitempty"`
Username string `json:"username,omitempty"`
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
Email string `json:"email,omitempty"`
Password string `json:"password,omitempty"`
Phone string `json:"phone,omitempty"`
// User Status
UserStatus int32 `json:"userStatus,omitempty"`
}

View File

@ -0,0 +1,46 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"net/http"
)
// APIResponse stores the API response returned by the server.
type APIResponse struct {
*http.Response `json:"-"`
Message string `json:"message,omitempty"`
// Operation is the name of the OpenAPI operation.
Operation string `json:"operation,omitempty"`
// RequestURL is the request URL. This value is always available, even if the
// embedded *http.Response is nil.
RequestURL string `json:"url,omitempty"`
// Method is the HTTP method used for the request. This value is always
// available, even if the embedded *http.Response is nil.
Method string `json:"method,omitempty"`
// Payload holds the contents of the response body (which may be nil or empty).
// This is provided here as the raw response.Body() reader will have already
// been drained.
Payload []byte `json:"-"`
}
// NewAPIResponse returns a new APIResonse object.
func NewAPIResponse(r *http.Response) *APIResponse {
response := &APIResponse{Response: r}
return response
}
// NewAPIResponseWithError returns a new APIResponse object with the provided error message.
func NewAPIResponseWithError(errorMessage string) *APIResponse {
response := &APIResponse{Message: errorMessage}
return response
}

View File

@ -0,0 +1,96 @@
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
)
// A Route defines the parameters for an api endpoint
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
// Routes are a collection of defined api endpoints
type Routes []Route
// Router defines the required methods for retrieving api routes
type Router interface {
Routes() Routes
}
// NewRouter creates a new router for any number of api routers
func NewRouter(routers ...Router) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, api := range routers {
for _, route := range api.Routes() {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
}
return router
}
// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code
func EncodeJSONResponse(i interface{}, status *int, w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if status != nil {
w.WriteHeader(*status)
} else {
w.WriteHeader(http.StatusOK)
}
return json.NewEncoder(w).Encode(i)
}
// ReadFormFileToTempFile reads file data from a request form and writes it to a temporary file
func ReadFormFileToTempFile(r *http.Request, key string) (*os.File, error) {
r.ParseForm()
formFile, _, err := r.FormFile(key)
if err != nil {
return nil, err
}
defer formFile.Close()
file, err := ioutil.TempFile("tmp", key)
if err != nil {
return nil, err
}
defer file.Close()
fileBytes, err := ioutil.ReadAll(formFile)
if err != nil {
return nil, err
}
file.Write(fileBytes)
return file, nil
}
// parseIntParameter parses a sting parameter to an int64
func parseIntParameter(param string) (int64, error) {
return strconv.ParseInt(param, 10, 64)
}

0
cmd/sub-demo/home.html Normal file → Executable file
View File

2
cmd/sub-demo/main.go Normal file → Executable file
View File

@ -35,5 +35,5 @@ func StartServer() {
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
jch_http.RenderTemplate(w, "home", nil)
_http.RenderTemplate(w, "home", nil)
}

0
cmd/sub-demo/public/app.css Normal file → Executable file
View File

0
cmd/sub-demo/subscription.html Normal file → Executable file
View File

0
cmd/sub-demo/user.html Normal file → Executable file
View File

13
cmd/today/main.go Executable file
View File

@ -0,0 +1,13 @@
package main
import (
"fmt"
"time"
"github.com/jchenry/libs/arvelie"
)
func main() {
a := arvelie.FromDate(time.Now())
fmt.Println(a)
}

BIN
cmd/today/today Executable file

Binary file not shown.

53
cmd/web-tinkertoy/db.go Normal file
View File

@ -0,0 +1,53 @@
package main
import (
"context"
"database/sql"
"fmt"
"rsc.io/dbstore"
)
type DBFunc func(db *sql.DB)
type DBActor struct {
DB *sql.DB
ActionChan chan DBFunc
}
func (a *DBActor) Run(ctx context.Context) error {
for {
select {
case f := <-a.ActionChan:
f(a.DB)
case <-ctx.Done():
return ctx.Err()
}
}
}
func DBStoreInsert(store *dbstore.Storage, e interface{}) DBFunc {
return func(db *sql.DB) {
err := store.Insert(db, e)
fmt.Println(err)
}
}
func DBStoreDelete(store *dbstore.Storage, e interface{}) DBFunc {
return func(db *sql.DB) {
store.Delete(db, e)
}
}
func DBStoreSelect(store *dbstore.Storage, e interface{}, query string, args ...interface{}) DBFunc {
return func(db *sql.DB) {
err := store.Select(db, e, query, args...)
fmt.Println(err)
}
}
// func DBStoreRead(store *dbstore.Storage, e interface{}, IDCol string) DBFunc {
// return func(db *sql.DB) {
// store.Read(db, e, IDCol)
// }
// }

View File

@ -0,0 +1,15 @@
<html>
<body>
{{if (eq .Message "")}}
<form action="/echo" method="post">
<input type="text" id="msg" name="msg">
<input type="submit" value="Submit">
</form>
{{else}}
{{.Message}}
{{end}}
</body>
</html>

BIN
cmd/web-tinkertoy/foo.db Normal file

Binary file not shown.

View File

@ -0,0 +1,15 @@
<html>
<body>
{{if (eq .Message "")}}
<form
enctype="multipart/form-data"
method="post">
<input type="file" name="fortunes" />
<input type="submit" value="upload" />
</form>
{{else}}
{{.Message}}
{{end}}
</body>
</html>

8
cmd/web-tinkertoy/go.mod Normal file
View File

@ -0,0 +1,8 @@
module github.com/jchenry/jch
go 1.14
require (
github.com/mattn/go-sqlite3 v2.0.3+incompatible
rsc.io/dbstore v0.1.1
)

6
cmd/web-tinkertoy/go.sum Normal file
View File

@ -0,0 +1,6 @@
github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c=
github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U=
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
rsc.io/dbstore v0.1.1 h1:LI4gBJUwbejn0wHJWe0KTwgCM33zUVP3BsNz5y2fkEE=
rsc.io/dbstore v0.1.1/go.mod h1:zI7k1PCSLg9r/T2rBM4E/SctbGmqdtt3kjQSemVh1Rs=
rsc.io/sqlite v0.5.0/go.mod h1:fqHuveM9iIqMzjD0WiZIvKYMty/WqTo2bxE9+zC54WE=

BIN
cmd/web-tinkertoy/jch Executable file

Binary file not shown.

44
cmd/web-tinkertoy/main.go Normal file
View File

@ -0,0 +1,44 @@
package main
import (
"database/sql"
"fmt"
"io"
"net/http"
"os"
_ "github.com/mattn/go-sqlite3"
)
func main() {
if err := run(os.Args, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}
func run(args []string, stdout io.Writer) error {
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel()
// if db, err := sql.Open("sqlite3", "foo.db"); err == nil {
// dba := DBActor{
// DB: db,
// ActionChan: make(chan DBFunc, 1),
// }
// go dba.Run(ctx)
// }
s := server{
router: http.NewServeMux(),
}
s.routes()
if db, err := sql.Open("sqlite3", "foo.db"); err == nil {
s.db = db
} else {
return err
}
return http.ListenAndServe(":8080", s.router)
}

137
cmd/web-tinkertoy/server.go Normal file
View File

@ -0,0 +1,137 @@
package main
import (
"bufio"
"context"
"database/sql"
"fmt"
"io"
"log"
"net/http"
"sync"
"text/template"
"time"
"rsc.io/dbstore"
)
type server struct {
db *sql.DB
router *http.ServeMux
echoMessage string
}
func (s *server) routes() {
s.router.HandleFunc("/time", s.handleTime())
s.router.HandleFunc("/echo", s.handleEcho())
s.router.HandleFunc("/fortune", s.handleFortune())
}
func (s *server) handleTime() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
io.WriteString(w, time.Now().String())
}
}
func (s *server) handleEcho() http.HandlerFunc {
var (
init sync.Once
tmpl *template.Template
tplerr error
)
return func(w http.ResponseWriter, r *http.Request) {
init.Do(func() {
tmpl, tplerr = template.ParseFiles("echoform.tmpl")
})
if tplerr != nil {
http.Error(w, tplerr.Error(), http.StatusInternalServerError)
return
}
switch r.Method {
case http.MethodPost:
r.ParseForm()
s.echoMessage = r.Form.Get("msg")
http.Redirect(w, r, "/echo", 301)
return
case http.MethodGet:
if err := tmpl.Execute(w, map[string]string{"Message": s.echoMessage}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
}
func (s *server) handleFortune() http.HandlerFunc {
var (
init sync.Once
dba *DBActor
storage *dbstore.Storage
tmpl *template.Template
tplerr error
)
type fortuneWrapper struct {
Fortune string
}
return func(w http.ResponseWriter, r *http.Request) {
init.Do(func() {
ctx, _ := context.WithCancel(context.Background())
dba = &DBActor{
DB: s.db,
ActionChan: make(chan DBFunc),
}
go dba.Run(ctx)
storage = new(dbstore.Storage)
storage.Register(&fortuneWrapper{})
err := storage.CreateTables(dba.DB)
if err != nil {
fmt.Println(err)
}
tmpl, tplerr = template.ParseFiles("fortunesupload.tmpl")
})
if tplerr != nil {
http.Error(w, tplerr.Error(), http.StatusInternalServerError)
return
}
switch r.Method {
case http.MethodPost:
r.ParseMultipartForm(10 << 20)
file, _, err := r.FormFile("fortunes")
if err != nil {
fmt.Println("Error Retrieving the File")
fmt.Println(err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
var fortune string
for scanner.Scan() {
switch scanner.Text() {
case "%":
dba.ActionChan <- DBStoreInsert(storage, &fortuneWrapper{Fortune: fortune})
default:
fortune = scanner.Text()
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
case http.MethodGet:
f := fortuneWrapper{}
DBStoreSelect(storage, &f, "ORDER BY RANDOM() LIMIT 1", "*")(s.db)
if err := tmpl.Execute(w, map[string]string{"Message": f.Fortune}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
}

0
data/db_collection_store.go Normal file → Executable file
View File

0
go.mod Normal file → Executable file
View File

0
go.sum Normal file → Executable file
View File

0
http/julienschmidt_router.go Normal file → Executable file
View File

0
http/server.go Normal file → Executable file
View File

0
http/server_test.go Normal file → Executable file
View File

0
http/templates.go Normal file → Executable file
View File

0
http/util.go Normal file → Executable file
View File

0
model/database_model.go Normal file → Executable file
View File

11
neralie/doc.go Executable file
View File

@ -0,0 +1,11 @@
package neralie
// This decimal clock has two groups of 3 digits, called the beat & the pulse.
// A beat contains 1000 pulses, and equivalent to 86.4 seconds.
//
// Examples:
// 6:00 250:000
// 12:00 500:000
// 18:00 750:000
//
// Boosted lovingly from https://github.com/XXIIVV/Oscean/blob/master/scripts/lib/neralie.js

27
neralie/neralie.go Executable file
View File

@ -0,0 +1,27 @@
package neralie
import (
"fmt"
"time"
)
type Neralie int64
func (n Neralie) String() string {
ms := time.Duration(n).Milliseconds()
v := fmt.Sprintf("%.6f", float64(ms)/8640.0/10000.0)
return fmt.Sprintf("%s:%s", v[2:5], v[5:8])
}
func ToTime(n Neralie) time.Time {
return bod(time.Now()).Add(time.Duration(n))
}
func FromTime(t time.Time) Neralie {
return Neralie(t.Sub(bod(t)))
}
func bod(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
}

53
neralie/neralie_test.go Executable file
View File

@ -0,0 +1,53 @@
package neralie_test
import (
"fmt"
"strings"
"testing"
"time"
"github.com/jchenry/libs/neralie"
)
func TestFromTime(t *testing.T) {
tests := [][]string{
{"250:000", "6:00"},
{"500:000", "12:00"},
{"750:000", "18:00"},
}
for i := range tests {
y, m, d := time.Now().Date()
dt, _ := time.Parse("15:04", tests[i][1])
h, m2, s := dt.Clock()
n := neralie.FromTime(time.Date(y, m, d, h, m2, s, 0, time.UTC))
expected := tests[i][0]
if !strings.EqualFold(n.String(), expected) {
fmt.Printf("%s != %s\n", expected, n.String())
t.Fail()
}
}
}
func TestToTime(t *testing.T) {
tests := [][]string{
{"250:000", "6:00"},
{"500:000", "12:00"},
{"750:000", "18:00"},
}
for i := range tests {
y, m, d := time.Now().Date()
dt, _ := time.Parse("15:04", tests[i][1])
h, m2, s := dt.Clock()
d1 := time.Date(y, m, d, h, m2, s, 0, time.UTC)
n := neralie.FromTime(d1)
d2 := neralie.ToTime(n)
if !d1.Equal(d2) {
fmt.Printf("%s != %s\n", d1, d2)
t.Fail()
}
}
}

0
payments/config.go Normal file → Executable file
View File

0
payments/doc.go Normal file → Executable file
View File

0
payments/middleware.go Normal file → Executable file
View File

0
payments/service.go Normal file → Executable file
View File

1483
pic/parser.go Executable file

File diff suppressed because it is too large Load Diff

351
pic/pic.y Executable file
View File

@ -0,0 +1,351 @@
%union{
str string
result Result
}
%{
/*
* Changes by Gunnar Ritter, Freiburg i. Br., Germany, October 2005.
*
* Derived from Plan 9 v4 /sys/src/cmd/pic/
*
* Copyright (C) 2003, Lucent Technologies Inc. and others.
* All Rights Reserved.
*
* Distributed under the terms of the Lucent Public License Version 1.02.
*/
/* Sccsid @(#)picy.y 1.4 (gritter) 11/28/05 */
#include <stdio.h>
#include "pic.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#ifndef RAND_MAX
#define RAND_MAX 32767
#endif
YYSTYPE y;
extern void yyerror(char *);
extern int yylex(void);
%}
%token <i> BOX 1 /* DON'T CHANGE THESE! */
%token <i> LINE 2
%token <i> ARROW 3
%token <i> CIRCLE 4
%token <i> ELLIPSE 5
%token <i> ARC 6
%token <i> SPLINE 7
%token <i> BLOCK 8
%token <p> TEXT 9
%token <p> TROFF 10
%token <i> MOVE 11
%token <i> BLOCKEND 12
%token <i> PLACE 13
%token <i> PRINT RESET THRU UNTIL
%token <o> FOR IF COPY
%token <p> THENSTR ELSESTR DOSTR PLACENAME VARNAME SPRINTF
%token <st> DEFNAME
%token <i> ATTR TEXTATTR
%token <i> LEFT RIGHT UP DOWN FROM TO AT BY WITH HEAD CW CCW THEN
%token <i> HEIGHT WIDTH RADIUS DIAMETER LENGTH SIZE
%token <i> CORNER HERE LAST NTH SAME BETWEEN AND
%token <i> EAST WEST NORTH SOUTH NE NW SE SW START END
%token <i> DOTX DOTY DOTHT DOTWID DOTRAD
%token <f> NUMBER
%token <f> LOG EXP SIN COS ATAN2 SQRT RAND MIN MAX INT
%token <i> DIR
%token <i> DOT DASH CHOP FILL NOEDGE
%token <o> ST /* statement terminator */
%right <f> '='
%left <f> OROR
%left <f> ANDAND
%nonassoc <f> GT LT LE GE EQ NEQ
%left <f> '+' '-'
%left <f> '*' '/' '%'
%right <f> UMINUS NOT
%right <f> '^'
%type <f> expr if_expr asgn
%type <p> name text
%type <i> optop exprlist
%type <o> if for copy
/* this is a lie: picture and position are really the whole union */
%type <o> leftbrace picture piclist position lbracket
%type <o> prim place blockname
%type <i> textlist textattr /* not a sensible value */
%type <i> last type
%%
top:
piclist
| /* empty */
| error { WARNING("syntax error"); }
;
piclist:
picture
| piclist picture
;
picture:
prim ST { codegen = 1; makeiattr(0, 0); }
| leftbrace piclist '}' { rightthing($1, '}'); $$ = $2; }
| PLACENAME ':' picture { y.o=$3; makevar($1,PLACENAME,y); $$ = $3; }
| PLACENAME ':' ST picture { y.o=$4; makevar($1,PLACENAME,y); $$ = $4; }
| PLACENAME ':' position ST { y.o=$3; makevar($1,PLACENAME,y); $$ = $3; }
| asgn ST { y.f = $1; $$ = y.o; $$ = makenode(PLACE, 0); }
| DIR { setdir($1); $$ = makenode(PLACE, 0); }
| PRINT expr ST { printexpr($2); $$ = makenode(PLACE, 0); }
| PRINT position ST { printpos($2); $$ = makenode(PLACE, 0); }
| PRINT text ST { printf("%s\n", $2); free($2); $$ = makenode(PLACE, 0); }
| RESET varlist ST { resetvar(); makeiattr(0, 0); $$ = makenode(PLACE, 0); }
| copy
| for
| if
| ST
;
varlist:
/* empty */
| VARNAME { makevattr($1); }
| varlist VARNAME { makevattr($2); }
| varlist ',' VARNAME { makevattr($3); }
;
asgn:
VARNAME '=' expr { $$=y.f=$3; makevar($1,VARNAME,y); checkscale($1); }
;
copy:
COPY copylist { copy(); }
;
copylist:
copyattr
| copylist copyattr
;
copyattr:
text { copyfile($1); }
| THRU DEFNAME { copydef($2); }
| UNTIL text { copyuntil($2); }
;
for:
FOR name FROM expr TO expr BY optop expr DOSTR
{ forloop($2, $4, $6, $8, $9, $10); }
| FOR name FROM expr TO expr DOSTR
{ forloop($2, $4, $6, '+', 1.0, $7); }
| FOR name '=' expr TO expr BY optop expr DOSTR
{ forloop($2, $4, $6, $8, $9, $10); }
| FOR name '=' expr TO expr DOSTR
{ forloop($2, $4, $6, '+', 1.0, $7); }
;
if:
IF if_expr THENSTR ELSESTR { ifstat($2, $3, $4); }
| IF if_expr THENSTR { ifstat($2, $3, (char *) 0); }
;
if_expr:
expr
| text EQ text { $$ = strcmp($1,$3) == 0; free($1); free($3); }
| text NEQ text { $$ = strcmp($1,$3) != 0; free($1); free($3); }
;
name:
VARNAME { y.f = 0; makevar($1, VARNAME, y); }
;
optop:
'+' { $$ = '+'; }
| '-' { $$ = '-'; }
| '*' { $$ = '*'; }
| '/' { $$ = '/'; }
| /* empty */ { $$ = ' '; }
;
leftbrace:
'{' { $$ = leftthing('{'); }
;
prim:
BOX attrlist { $$ = boxgen(); }
| CIRCLE attrlist { $$ = circgen($1); }
| ELLIPSE attrlist { $$ = circgen($1); }
| ARC attrlist { $$ = arcgen($1); }
| LINE attrlist { $$ = linegen($1); }
| ARROW attrlist { $$ = linegen($1); }
| SPLINE attrlist { $$ = linegen($1); }
| MOVE attrlist { $$ = movegen(); }
| textlist attrlist { $$ = textgen(); }
| TROFF { $$ = troffgen($1); }
| lbracket piclist ']' { $<o>$=rightthing($1,']'); } attrlist
{ $$ = blockgen($1, $<o>4); }
;
lbracket:
'[' { $$ = leftthing('['); }
;
attrlist:
attrlist attr
| /* empty */
;
attr:
ATTR expr { makefattr($1, !DEFAULT, $2); }
| ATTR { makefattr($1, DEFAULT, 0.0); }
| expr { makefattr(curdir(), !DEFAULT, $1); }
| DIR expr { makefattr($1, !DEFAULT, $2); }
| DIR { makefattr($1, DEFAULT, 0.0); }
| FROM position { makeoattr($1, $2); }
| TO position { makeoattr($1, $2); }
| AT position { makeoattr($1, $2); }
| BY position { makeoattr($1, $2); }
| WITH CORNER { makeiattr(WITH, $2); }
| WITH '.' PLACENAME { makeoattr(PLACE, getblock(getlast(1,BLOCK), $3)); }
| WITH '.' PLACENAME CORNER
{ makeoattr(PLACE, getpos(getblock(getlast(1,BLOCK), $3), $4)); }
| WITH position { makeoattr(PLACE, $2); }
| SAME { makeiattr(SAME, $1); }
| TEXTATTR { maketattr($1, (char *) 0); }
| HEAD { makeiattr(HEAD, $1); }
| DOT expr { makefattr(DOT, !DEFAULT, $2); }
| DOT { makefattr(DOT, DEFAULT, 0.0); }
| DASH expr { makefattr(DASH, !DEFAULT, $2); }
| DASH { makefattr(DASH, DEFAULT, 0.0); }
| CHOP expr { makefattr(CHOP, !DEFAULT, $2); }
| CHOP { makefattr(CHOP, DEFAULT, 0.0); }
| CHOP PLACENAME { makeattr(CHOP, PLACENAME, getvar($2)); }
| FILL expr { makefattr(FILL, !DEFAULT, $2); }
| FILL { makefattr(FILL, DEFAULT, 0.0); }
| NOEDGE { makeiattr(NOEDGE, 0); }
| textlist
;
textlist:
textattr
| textlist textattr
;
textattr:
text { maketattr(CENTER, $1); }
| text TEXTATTR { maketattr($2, $1); }
| textattr TEXTATTR { addtattr($2); }
;
text:
TEXT
| SPRINTF '(' text ')' { $$ = sprintgen($3); }
| SPRINTF '(' text ',' exprlist ')' { $$ = sprintgen($3); }
;
exprlist:
expr { exprsave($1); $$ = 0; }
| exprlist ',' expr { exprsave($3); }
;
position: /* absolute, not relative */
place
| '(' position ')' { $$ = $2; }
| expr ',' expr { $$ = makepos($1, $3); }
| position '+' expr ',' expr { $$ = fixpos($1, $3, $5); }
| position '-' expr ',' expr { $$ = fixpos($1, -$3, -$5); }
| position '+' '(' expr ',' expr ')' { $$ = fixpos($1, $4, $6); }
| position '-' '(' expr ',' expr ')' { $$ = fixpos($1, -$4, -$6); }
| position '+' place { $$ = addpos($1, $3); }
| position '-' place { $$ = subpos($1, $3); }
| '(' place ',' place ')' { $$ = makepos(getcomp($2,DOTX), getcomp($4,DOTY)); }
| expr LT position ',' position GT { $$ = makebetween($1, $3, $5); }
| expr BETWEEN position AND position { $$ = makebetween($1, $3, $5); }
;
place:
PLACENAME { y = getvar($1); $$ = y.o; }
| PLACENAME CORNER { y = getvar($1); $$ = getpos(y.o, $2); }
| CORNER PLACENAME { y = getvar($2); $$ = getpos(y.o, $1); }
| HERE { $$ = gethere(); }
| last type { $$ = getlast($1, $2); }
| last type CORNER { $$ = getpos(getlast($1, $2), $3); }
| CORNER last type { $$ = getpos(getlast($2, $3), $1); }
| NTH type { $$ = getfirst($1, $2); }
| NTH type CORNER { $$ = getpos(getfirst($1, $2), $3); }
| CORNER NTH type { $$ = getpos(getfirst($2, $3), $1); }
| blockname
| blockname CORNER { $$ = getpos($1, $2); }
| CORNER blockname { $$ = getpos($2, $1); }
;
blockname:
last BLOCK '.' PLACENAME { $$ = getblock(getlast($1,$2), $4); }
| NTH BLOCK '.' PLACENAME { $$ = getblock(getfirst($1,$2), $4); }
| PLACENAME '.' PLACENAME { y = getvar($1); $$ = getblock(y.o, $3); }
;
last:
last LAST { $$ = $1 + 1; }
| NTH LAST { $$ = $1; }
| LAST { $$ = 1; }
;
type:
BOX
| CIRCLE
| ELLIPSE
| ARC
| LINE
| ARROW
| SPLINE
| BLOCK
;
expr:
NUMBER
| VARNAME { $$ = getfval($1); }
| asgn
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { if ($3 == 0.0) {
WARNING("division by 0"); $3 = 1; }
$$ = $1 / $3; }
| expr '%' expr { if ((long)$3 == 0) {
WARNING("mod division by 0"); $3 = 1; }
$$ = (long)$1 % (long)$3; }
| '-' expr %prec UMINUS { $$ = -$2; }
| '+' expr %prec UMINUS { $$ = $2; }
| '(' expr ')' { $$ = $2; }
| place DOTX { $$ = getcomp($1, $2); }
| place DOTY { $$ = getcomp($1, $2); }
| place DOTHT { $$ = getcomp($1, $2); }
| place DOTWID { $$ = getcomp($1, $2); }
| place DOTRAD { $$ = getcomp($1, $2); }
| PLACENAME '.' VARNAME { y = getvar($1); $$ = getblkvar(y.o, $3); }
| last BLOCK '.' VARNAME { $$ = getblkvar(getlast($1,$2), $4); }
| NTH BLOCK '.' VARNAME { $$ = getblkvar(getfirst($1,$2), $4); }
| expr GT expr { $$ = $1 > $3; }
| expr LT expr { $$ = $1 < $3; }
| expr LE expr { $$ = $1 <= $3; }
| expr GE expr { $$ = $1 >= $3; }
| expr EQ expr { $$ = $1 == $3; }
| expr NEQ expr { $$ = $1 != $3; }
| expr ANDAND expr { $$ = $1 && $3; }
| expr OROR expr { $$ = $1 || $3; }
| NOT expr { $$ = !($2); }
| LOG '(' expr ')' { $$ = Log10($3); }
| EXP '(' expr ')' { $$ = Exp($3 * log(10.0)); }
| expr '^' expr { $$ = pow($1, $3); }
| SIN '(' expr ')' { $$ = sin($3); }
| COS '(' expr ')' { $$ = cos($3); }
| ATAN2 '(' expr ',' expr ')' { $$ = atan2($3, $5); }
| SQRT '(' expr ')' { $$ = Sqrt($3); }
| RAND '(' ')' { $$ = (float)rand() / RAND_MAX; }
| MAX '(' expr ',' expr ')' { $$ = $3 >= $5 ? $3 : $5; }
| MIN '(' expr ',' expr ')' { $$ = $3 <= $5 ? $3 : $5; }
| INT '(' expr ')' { $$ = (long) $3; }
;

6893
pic/y.output Executable file

File diff suppressed because it is too large Load Diff

46
rest/collection.go Normal file → Executable file
View File

@ -7,7 +7,7 @@ import (
"strconv"
"strings"
jch_http "github.com/jchenry/jchenry/http"
_http "github.com/jchenry/jchenry/http"
)
const (
@ -48,7 +48,7 @@ func Collection(entityPtr interface{}, service CollectionStore) *CollectionInsta
}
}
func (collection *CollectionInstance) Register(uriBase string, restServer *jch_http.Server) {
func (collection *CollectionInstance) Register(uriBase string, restServer *_http.Server) {
plural := properPlural(collection.name)
urlBase := uriBase + "/" + plural //collection.name + "s"
@ -73,77 +73,77 @@ func properPlural(word string) string {
func (collection *CollectionInstance) create(response http.ResponseWriter, request *http.Request) {
entityPtr := reflect.New(collection.instanceType).Interface() //collection.instanceProviderPtr.NewInstance()
err := jch_http.ReadEntity(request, entityPtr)
err := _http.ReadEntity(request, entityPtr)
if err != nil {
jch_http.WriteErrorResponse(response, http.StatusBadRequest, err.Error())
_http.WriteErrorResponse(response, http.StatusBadRequest, err.Error())
return
}
err = collection.service.Create(entityPtr)
if err != nil {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
return
}
response.WriteHeader(http.StatusCreated)
jch_http.WriteEntity(response, entityPtr)
_http.WriteEntity(response, entityPtr)
}
func (collection *CollectionInstance) update(response http.ResponseWriter, request *http.Request) {
entityPtr := reflect.New(collection.instanceType).Interface() //collection.instanceProviderPtr.NewInstance()
err := jch_http.ReadEntity(request, entityPtr)
err := _http.ReadEntity(request, entityPtr)
if err != nil {
jch_http.WriteErrorResponse(response, http.StatusBadRequest, err.Error())
_http.WriteErrorResponse(response, http.StatusBadRequest, err.Error())
return
}
id := request.Form.Get(IDPathParameter)
err = collection.service.Find(&[]interface{}{}, map[string]interface{}{IDPathParameter: id})
if err != nil {
if err == jch_http.ErrNotFound {
jch_http.WriteErrorResponse(response, http.StatusNotFound, fmt.Sprintf("%v with id %v not found", collection.name, id))
if err == _http.ErrNotFound {
_http.WriteErrorResponse(response, http.StatusNotFound, fmt.Sprintf("%v with id %v not found", collection.name, id))
} else {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
}
return
}
err = collection.service.Update(entityPtr)
if err != nil {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
return
}
response.WriteHeader(http.StatusOK)
jch_http.WriteEntity(response, entityPtr)
_http.WriteEntity(response, entityPtr)
}
func (collection *CollectionInstance) remove(response http.ResponseWriter, request *http.Request) {
id := request.Form.Get(IDPathParameter)
err := collection.service.Find(&[]interface{}{}, map[string]interface{}{IDPathParameter: id})
if err != nil {
if err == jch_http.ErrNotFound {
jch_http.WriteErrorResponse(response, http.StatusNotFound, fmt.Sprintf("%v with id %v not found", collection.name, id))
if err == _http.ErrNotFound {
_http.WriteErrorResponse(response, http.StatusNotFound, fmt.Sprintf("%v with id %v not found", collection.name, id))
} else {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
}
return
}
entityPtr := reflect.New(collection.instanceType).Interface() //collection.instanceProviderPtr.NewInstance()
field := reflect.Indirect(reflect.ValueOf(entityPtr)).FieldByName(strings.ToUpper(IDPathParameter))
if !field.CanSet() {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, "entity does not have "+IDPathParameter+" field or field is not setable")
_http.WriteErrorResponse(response, http.StatusInternalServerError, "entity does not have "+IDPathParameter+" field or field is not setable")
}
parsedID, err := strconv.ParseInt(id, 0, 64)
if err != nil {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
}
field.SetInt(parsedID)
err = collection.service.Delete(entityPtr)
if err != nil {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
return
}
@ -157,10 +157,10 @@ func (collection *CollectionInstance) find(response http.ResponseWriter, request
err := collection.service.Find(arri, valuesToMap(request.URL.Query(), id))
if err != nil {
if err == jch_http.ErrNotFound {
jch_http.WriteErrorResponse(response, http.StatusNotFound, fmt.Sprintf("%v with id %v not found", collection.name, id))
if err == _http.ErrNotFound {
_http.WriteErrorResponse(response, http.StatusNotFound, fmt.Sprintf("%v with id %v not found", collection.name, id))
} else {
jch_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
_http.WriteErrorResponse(response, http.StatusInternalServerError, err.Error())
}
return
}
@ -183,7 +183,7 @@ func (collection *CollectionInstance) find(response http.ResponseWriter, request
}
response.WriteHeader(http.StatusOK)
jch_http.WriteEntity(response, results)
_http.WriteEntity(response, results)
}
func valuesToMap(params map[string][]string, id string) map[string]interface{} {

0
rest/collection_test.go Normal file → Executable file
View File

0
rest/resultset_response.go Normal file → Executable file
View File

1
tablatal/doc.go Executable file
View File

@ -0,0 +1 @@
package tabatal

34
tablatal/tabatal.go Executable file
View File

@ -0,0 +1,34 @@
package tabatal
import (
"encoding/csv"
"io"
"strings"
)
func Parse(data string) (a []map[string]interface{}, err error) {
// a := []map[string]interface{}{}
r := csv.NewReader(strings.NewReader(data))
r.Comma = '\t'
r.Comment = ';'
var header []string
for i := 0; ; i++ {
row, err := r.Read()
if err == io.EOF {
break
} else if err != nil {
return a, err
}
if i == 0 {
header = row
continue
}
record := map[string]interface{}{}
for i, h := range header {
record[h] = row[i]
}
a = append(a, record)
}
return a, nil
}