Merge branch 'release/0.4.0'

* release/0.4.0:
  Keeping track of the new shit.
  FINAL: CLI model.  Also: changed 'clock' to 'time' or 'timeofday', depending.
This commit is contained in:
Elf M. Sternberg 2018-03-30 19:08:47 -07:00
commit 6f1bb716b6
21 changed files with 918 additions and 500 deletions

2
DESCRIPION.md Normal file
View File

@ -0,0 +1,2 @@
A simple Swagger example tutorial, but with a twist: explaining how to
get new CLI arguments down to your handlers.

28
README.md Normal file
View File

@ -0,0 +1,28 @@
# TIME-OF-DAY
TimeOfDay is a dead-simple microservice written in Go that, when pinged
at the correct URL, returns the time of day. The server can take a
single parameter either via GET or POST to specify the timezone from
which the client wants the time.
This repository exists as a supplement to my tutorial,
[Adding Command Line Arguments to Go-Swagger](TK:), in which I do
exactly that.
# Status
This project is **complete**. No future work will be done on it.
# License
Apache 2.0. See the accompanying LICENSE file in this directory.
# Warranty
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

227
docs/Part_01.md Normal file
View File

@ -0,0 +1,227 @@
# Introduction
[${WORK}](http://www.splunk.com) has me writing microservices in Go,
using OpenAPI 2.0 / Swagger. While I'm not a fan of Go (that's a bit of
an understatement) I get why Go is popular with enterprise managers, it
does exactly what it says it does. It's syntactically hideous. I'm
perfectly happy taking a paycheck to write in it, and I'm pretty good at
it already. I just wouldn't choose it for a personal project.
But if you're writing microservices for enterprise customers, yes, you
should use Go, and yes, you should use OpenAPI and Swagger. So here's
how it's done.
[Swagger](https://swagger.io/) is a specification that describes the
ndpoints for a webserver's API, usually a REST-based API. HTTP uses
verbs (GET, PUT, POST, DELETE) and endpoints (/like/this) to describe
things your service handles and the operations that can be performed
against it.
Swagger starts with a **file**, written in JSON or YAML, that names
each and every endpoint, the verbs that endpoint responds to, the
parameters that endpoint requires and takes optionally, and the
possible responses, with type information for every field in the
inputs and outputs.
Swagger *tooling* then takes that file and generates a server ready to
handle all those transactions. The parameters specified in the
specification file are turned into function calls and populated with
"Not implemented" as the only thing they return.
## Your job
In short, for a basic microservice, it's your job to replace those
functions with your business logic.
There are three things that are your responsibility:
1. Write the specification that describes *exactly* what the server
accepts as requests and returns as responses.
2. Write the business logic.
3. Glue the business logic into the server generated from the
specification.
In Go-Swagger, there is *exactly one* file in the generated code that
you need to change. Every other file is labeled "DO NOT EDIT." This
one file, called `configure_project.go`, has a top line that says "This
file is safe to edit, and will not be replaced if you re-run swagger."
That *exactly one* file should be the only one you ever need to change.
## The setup
You'll need Go. I'm not going to go into setting up Go on your system;
there are
[perfectly adequate guides elsewhere](https://golang.org/doc/install).
You will need to install `swagger` and `dep`.
Once you've set up your Go environment (set up $GOPATH and $PATH), you
can just:
```
$ go get -u github.com/golang/dep/cmd/dep
$ go get -u github.com/go-swagger/go-swagger/cmd/swagger
```
## Initialization
Now you're going to create a new project. Do it in your src directory
somewhere, under your $GOPATH.
```
$ mkdir project timeofday
$ cd timeofday
$ git init && git commit --allow-empty -m "Init commit: Swagger Time of Day."
$ swagger init spec --format=yaml --title="Timeofday" --description="A silly time-of-day microservice"
```
You will now find a new swagger file in your project directory. If
you open it up, you'll see short header describing the basic features
Swagger needs to understand your project.
## Operations
Swagger works with **operations**, which is a combination of a verb
and an endpoint. We're going to have two operations which do the same
thing: return the time of day. The two operations use the same
endpoint, but different verbs: GET and POST. The GET argument takes
an optional timezone as a search option; the POST argument takes an
optional timezone as a JSON argument in the body of the POST.
First, let's version our API. You do that with Basepaths:
<<version the API>>=
basePath: /timeofday/v1
@
Now that we have a base path that versions our API, we want to define
our endpoint. The URL will ultimately be `/timeofday/v1/time`, and we
want to handle both GET and POST requests, and our responses are going
to be **Success: Time of day** or **Timezone Not Found**.
<<define the paths>>=
paths:
/time:
get:
operationId: "GetTime"
parameters:
- in: path
name: Timezone
schema:
type: string
minLength: 3
responses:
200:
schema:
$ref: "#/definitions/TimeOfDay"
404:
schema:
$ref: "#/definitions/NotFound"
post:
operationId: "PostTime"
parameters:
- in: body
name: Timezone
schema:
$ref: "#/definitions/Timezone"
responses:
200:
schema:
$ref: "#/definitions/TimeOfDay"
404:
schema:
$ref: "#/definitions/NotFound"
@
The `$ref` entries are a YAML thing for referring to something else.
The octothorpe symbol `(#)` indicates "look in the current file. So
now we have to create those paths:
<<schemas>>=
definitions:
NotFound:
type: object
properties:
code:
type: integer
message:
type: string
Timezone:
type: object
properties:
Timezone:
type: string
minLength: 3
TimeOfDay:
type: object
properties:
TimeOfDay: string
@
This is *really verbose*, but on the other hand it is *undeniably
complete*: these are the things we take in, and the things we respond
with.
So now your file looks like this:
<<swagger.yml>>=
swagger: "2.0"
info:
version: 0.1.0
title: timeofday
produces:
- application/json
consumes:
- application/json
schemes:
- http
# Everything above this line was generated by the swagger command.
# Everything below this line you have to add:
<<version the API>>
<<schemas>>
<<define the paths>>
@
Now that you have that, it's time to generate the server!
`$ swagger generate server -f swagger.yml`
It will spill out the actions it takes as it generates your new REST
server. **Do not** follow the advice at the end of the output.
There's a better way.
`$ dep init`
Dependency management in Go is a bit of a mess, but the accepted
solution now is to use `dep` rather than `go get`. This creates a
pair of files, one describing the Go packages that your file uses, and
one describing the exact *versions* of those packages that you last
downloaded and used in the `./vendor/` directory under your project
root.
Now you can build the server:
`$ go build ./cmd/timeofday-server/`
And then you can run it. Feel free to change the port number:
`$ ./timeofday-server --port=8082`
You can now tickle the server:
```
$ curl http://localhost:8082/
{"code":404,"message":"path / was not found"}
$ curl http://localhost:8082/timeofday/v1/time
" function .GetTime is not implemented"
```
Congratulations! You have a working REST server that does, well,
nothing.
For part two, we'll make our server actually do things.

148
docs/Part_02.md Normal file
View File

@ -0,0 +1,148 @@
# Review of Part One
In [Part One of Go-Swagger](TK:), we generated a on OpenAPI 2.0 server
with REST endpoints. The server builds and responds to queries, but
every valid query ends with "This feature has not yet been
implemented."
It's time to implement the feature.
I want to emphasize that with Go Swagger there is *only* one generated
file you need to touch. Since our project is named `timezone`, the
file will be named `restapi/configure_timezone.go`. Our first step
will be to break those "not implemented" functions out into their own
Go package. That package will be our business logic. The configure
file and the business logic package will be the *only* things we
change.
## Break out the business logic
Create a new folder in your project root and call it `timeofday`.
Open up your editor and find the file `restapi/configure_timeofday.go`.
In your `swagger.yml` file you created two endpoints and gave them each
an `operationId`: `TimekPost` and `TimeGet`. Inside
`configure_timeofday.go`, you should find two corresponding assignments
in the function `configureAPI()`: `TimeGetHandlerFunc` and
`ClockPostHandlerFunc`. Inside those function calls, you'll find
anonymous functions.
I want you to take those anonymous functions, cut them out, and paste
them into a new file inside the `timeofday/` folder. You will also have
to create a package name and import any packages being used. Now your
file, which I've called `timeofday/handlers.go`, looks like this:
<<handlers.go before implementation>>=
package timeofday
import(
"github.com/go-openapi/runtime/middleware"
"github.com/elfsternberg/timeofday/restapi/operations"
)
func GetTime(params operations.TimeGetParams) middleware.Responder {
return middleware.NotImplemented("operation .TimeGet has not yet been implemented")
}
func PostTime(params operations.TimePostParams) middleware.Responder {
return middleware.NotImplemented("operation .TimePost has not yet been implemented")
}
@
And now go back to `restapi/configure_timeofday.go`, add
`github.com/elfsternberg/timeofday/clock` to the imports, and change the
handler lines to look like this:
<<configuration lines before implementation>>=
api.TimeGetHandler = operations.TimeGetHandlerFunc(timeofday.GetTime)
api.TimePostHandler = operations.TimePostHandlerFunc(timeofday.PostTime)
@
## Implementation
Believe it or not, you've now done everything you need to do except the
business logic. We're going to honor the point of OpenAPI and the `//
DO NOT EDIT`` comments, and not modify anything exceept the contents of
our handler.
To understand our code, though, we're going to have to *read* some of
those files. Let's go look at `/models`. In here, you'll find the
schemas you outlined in the `swagger.yml` file turned into source code.
If you open one, like many files generated by Swagger, you'll see it
reads `// DO NOT EDIT`. But then there's that function there,
`Validate()`. What if you want to do advanced validation for custom
patterns or inter-field relations not covered by Swagger's validators?
Well, you'll have to edit this file. And figure out how to live with
it. We're not going to do that here. This exercise is about *not*
editing those files. But we can see, for example, that the `Timezone`
object has a field, `Timezone.Timezone`, which is a string, and which
has to be at least three bytes long.
The other thing you'll have to look at is the `restapi/operations`
folder. In here you'll find GET and POST operations, the parameters
they accept, the responses they deliver, and lots of functions only
Swagger cares about. But there are a few we care about.
Here's how we craft the GET response. Inside `handlers.go`, you're
going to need to extract the requested timezone, get the time of day,
and then return either a success message or an error message. Looking
in the operations files, there are a methods for good and bad returns,
as we described in the swagger file.
<<gettime implementation>>=
func GetTime(params operations.TimeGetParams) middleware.Responder {
var tz *string = nil
if (params.Timezone != nil) {
tz = params.Timezone
}
thetime, err := getTimeOfDay(params.Timezone)
@
The first thing to notice here is the `params` field: we're getting a
customized, tightly bound object from the server. There's no hope of
abstraction here. The next is that we made the Timezone input optional,
so here we have to check if it's `nil` or not. if it isn't, we need to
set it. We do this here because we need to *cast* params.Timezone into
a pointer to a string, because Go is weird about types.
We then call a (thus far undefined) function called `getTimeOfDay`.
Let's deal with the error case:
<<gettime implementation>>=
if err != nil {
return operations.NewTimeGetNotFound().WithPayload(
&models.ErrorResponse {
int32(operations.TimeGetNotFoundCode),
swag.String(fmt.Sprintf("%s", err)),
})
}
@
That's a lot of references. We have a model, an operation, and what's
that "swag" thing? In order to satisfy Swagger's strictness, we use
only what Swagger offers: for our 404 case, we didn't find the timezone
requested, so we're returning the ErrorResponse model populated with a
numeric code and a string, extracted via `fmt`, from the err returned
from our time function. The 404 case for get is called, yes,
`NewClockGetNotFound`, and then `WithPayload()` decorates the body of
the response with content.
The good path is similar:
<<gettime implementation>>=
return operations.NewClockGetOK().WithPayload(
&models.Timeofday{
Timeofday: *thetime,
})
}
@
Now might be a good time to go look in `models/` and `/restapi/options`,
to see what's available to you. You'll need to do so anyway, because
unless you go to the
[git repository](https://github.com/elfsternberg/go-swagger-tutorial)

View File

@ -8,6 +8,7 @@ import (
errors "github.com/go-openapi/errors"
runtime "github.com/go-openapi/runtime"
swag "github.com/go-openapi/swag"
graceful "github.com/tylerb/graceful"
"github.com/elfsternberg/timeofday/restapi/operations"
@ -16,8 +17,17 @@ import (
//go:generate swagger generate server --target .. --name --spec ../swagger.yml
var Timezone = timeofday.Timezone{
Timezone: "UTC",
}
func configureFlags(api *operations.TimeofdayAPI) {
// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }
api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{
swag.CommandLineOptionsGroup{
ShortDescription: "Time Of Day Service Options",
Options: &Timezone,
},
}
}
func configureAPI(api *operations.TimeofdayAPI) http.Handler {
@ -34,8 +44,8 @@ func configureAPI(api *operations.TimeofdayAPI) http.Handler {
api.JSONProducer = runtime.JSONProducer()
api.ClockGetHandler = operations.ClockGetHandlerFunc(timeofday.GetClock)
api.ClockPostHandler = operations.ClockPostHandlerFunc(timeofday.PostClock)
api.TimeGetHandler = operations.TimeGetHandlerFunc(timeofday.GetTime(&Timezone))
api.TimePostHandler = operations.TimePostHandlerFunc(timeofday.PostTime(&Timezone))
api.ServerShutdown = func() {}

View File

@ -46,7 +46,7 @@ func init() {
"/time": {
"get": {
"description": "Returns time of day.",
"operationId": "ClockGet",
"operationId": "TimeGet",
"parameters": [
{
"type": "string",
@ -78,7 +78,7 @@ func init() {
},
"post": {
"description": "Returns time of day.",
"operationId": "ClockPost",
"operationId": "TimePost",
"parameters": [
{
"description": "Timezone to return",
@ -180,7 +180,7 @@ func init() {
"/time": {
"get": {
"description": "Returns time of day.",
"operationId": "ClockGet",
"operationId": "TimeGet",
"parameters": [
{
"type": "string",
@ -212,7 +212,7 @@ func init() {
},
"post": {
"description": "Returns time of day.",
"operationId": "ClockPost",
"operationId": "TimePost",
"parameters": [
{
"description": "Timezone to return",

View File

@ -1,146 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
models "github.com/elfsternberg/timeofday/models"
)
// ClockGetOKCode is the HTTP code returned for type ClockGetOK
const ClockGetOKCode int = 200
/*ClockGetOK Returns the time of day.
swagger:response clockGetOK
*/
type ClockGetOK struct {
/*
In: Body
*/
Payload *models.Timeofday `json:"body,omitempty"`
}
// NewClockGetOK creates ClockGetOK with default headers values
func NewClockGetOK() *ClockGetOK {
return &ClockGetOK{}
}
// WithPayload adds the payload to the clock get o k response
func (o *ClockGetOK) WithPayload(payload *models.Timeofday) *ClockGetOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the clock get o k response
func (o *ClockGetOK) SetPayload(payload *models.Timeofday) {
o.Payload = payload
}
// WriteResponse to the client
func (o *ClockGetOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// ClockGetNotFoundCode is the HTTP code returned for type ClockGetNotFound
const ClockGetNotFoundCode int = 404
/*ClockGetNotFound Time zone not found
swagger:response clockGetNotFound
*/
type ClockGetNotFound struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewClockGetNotFound creates ClockGetNotFound with default headers values
func NewClockGetNotFound() *ClockGetNotFound {
return &ClockGetNotFound{}
}
// WithPayload adds the payload to the clock get not found response
func (o *ClockGetNotFound) WithPayload(payload *models.ErrorResponse) *ClockGetNotFound {
o.Payload = payload
return o
}
// SetPayload sets the payload to the clock get not found response
func (o *ClockGetNotFound) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *ClockGetNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(404)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// ClockGetInternalServerErrorCode is the HTTP code returned for type ClockGetInternalServerError
const ClockGetInternalServerErrorCode int = 500
/*ClockGetInternalServerError Something has gone horribly wrong
swagger:response clockGetInternalServerError
*/
type ClockGetInternalServerError struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewClockGetInternalServerError creates ClockGetInternalServerError with default headers values
func NewClockGetInternalServerError() *ClockGetInternalServerError {
return &ClockGetInternalServerError{}
}
// WithPayload adds the payload to the clock get internal server error response
func (o *ClockGetInternalServerError) WithPayload(payload *models.ErrorResponse) *ClockGetInternalServerError {
o.Payload = payload
return o
}
// SetPayload sets the payload to the clock get internal server error response
func (o *ClockGetInternalServerError) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *ClockGetInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(500)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@ -1,58 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
middleware "github.com/go-openapi/runtime/middleware"
)
// ClockPostHandlerFunc turns a function with the right signature into a clock post handler
type ClockPostHandlerFunc func(ClockPostParams) middleware.Responder
// Handle executing the request and returning a response
func (fn ClockPostHandlerFunc) Handle(params ClockPostParams) middleware.Responder {
return fn(params)
}
// ClockPostHandler interface for that can handle valid clock post params
type ClockPostHandler interface {
Handle(ClockPostParams) middleware.Responder
}
// NewClockPost creates a new http.Handler for the clock post operation
func NewClockPost(ctx *middleware.Context, handler ClockPostHandler) *ClockPost {
return &ClockPost{Context: ctx, Handler: handler}
}
/*ClockPost swagger:route POST /time clockPost
Returns time of day.
*/
type ClockPost struct {
Context *middleware.Context
Handler ClockPostHandler
}
func (o *ClockPost) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
var Params = NewClockPostParams()
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@ -1,146 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
models "github.com/elfsternberg/timeofday/models"
)
// ClockPostOKCode is the HTTP code returned for type ClockPostOK
const ClockPostOKCode int = 200
/*ClockPostOK Returns the time of day.
swagger:response clockPostOK
*/
type ClockPostOK struct {
/*
In: Body
*/
Payload *models.Timeofday `json:"body,omitempty"`
}
// NewClockPostOK creates ClockPostOK with default headers values
func NewClockPostOK() *ClockPostOK {
return &ClockPostOK{}
}
// WithPayload adds the payload to the clock post o k response
func (o *ClockPostOK) WithPayload(payload *models.Timeofday) *ClockPostOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the clock post o k response
func (o *ClockPostOK) SetPayload(payload *models.Timeofday) {
o.Payload = payload
}
// WriteResponse to the client
func (o *ClockPostOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// ClockPostNotFoundCode is the HTTP code returned for type ClockPostNotFound
const ClockPostNotFoundCode int = 404
/*ClockPostNotFound Time zone not found
swagger:response clockPostNotFound
*/
type ClockPostNotFound struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewClockPostNotFound creates ClockPostNotFound with default headers values
func NewClockPostNotFound() *ClockPostNotFound {
return &ClockPostNotFound{}
}
// WithPayload adds the payload to the clock post not found response
func (o *ClockPostNotFound) WithPayload(payload *models.ErrorResponse) *ClockPostNotFound {
o.Payload = payload
return o
}
// SetPayload sets the payload to the clock post not found response
func (o *ClockPostNotFound) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *ClockPostNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(404)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// ClockPostInternalServerErrorCode is the HTTP code returned for type ClockPostInternalServerError
const ClockPostInternalServerErrorCode int = 500
/*ClockPostInternalServerError Something has gone horribly wrong
swagger:response clockPostInternalServerError
*/
type ClockPostInternalServerError struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewClockPostInternalServerError creates ClockPostInternalServerError with default headers values
func NewClockPostInternalServerError() *ClockPostInternalServerError {
return &ClockPostInternalServerError{}
}
// WithPayload adds the payload to the clock post internal server error response
func (o *ClockPostInternalServerError) WithPayload(payload *models.ErrorResponse) *ClockPostInternalServerError {
o.Payload = payload
return o
}
// SetPayload sets the payload to the clock post internal server error response
func (o *ClockPostInternalServerError) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *ClockPostInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(500)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@ -0,0 +1,58 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
middleware "github.com/go-openapi/runtime/middleware"
)
// TimeGetHandlerFunc turns a function with the right signature into a time get handler
type TimeGetHandlerFunc func(TimeGetParams) middleware.Responder
// Handle executing the request and returning a response
func (fn TimeGetHandlerFunc) Handle(params TimeGetParams) middleware.Responder {
return fn(params)
}
// TimeGetHandler interface for that can handle valid time get params
type TimeGetHandler interface {
Handle(TimeGetParams) middleware.Responder
}
// NewTimeGet creates a new http.Handler for the time get operation
func NewTimeGet(ctx *middleware.Context, handler TimeGetHandler) *TimeGet {
return &TimeGet{Context: ctx, Handler: handler}
}
/*TimeGet swagger:route GET /time timeGet
Returns time of day.
*/
type TimeGet struct {
Context *middleware.Context
Handler TimeGetHandler
}
func (o *TimeGet) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
var Params = NewTimeGetParams()
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@ -15,18 +15,18 @@ import (
strfmt "github.com/go-openapi/strfmt"
)
// NewClockGetParams creates a new ClockGetParams object
// NewTimeGetParams creates a new TimeGetParams object
// no default values defined in spec.
func NewClockGetParams() ClockGetParams {
func NewTimeGetParams() TimeGetParams {
return ClockGetParams{}
return TimeGetParams{}
}
// ClockGetParams contains all the bound params for the clock get operation
// TimeGetParams contains all the bound params for the time get operation
// typically these are obtained from a http.Request
//
// swagger:parameters ClockGet
type ClockGetParams struct {
// swagger:parameters TimeGet
type TimeGetParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
@ -40,8 +40,8 @@ type ClockGetParams struct {
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewClockGetParams() beforehand.
func (o *ClockGetParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
// To ensure default values, the struct must have been initialized with NewTimeGetParams() beforehand.
func (o *TimeGetParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
@ -59,7 +59,7 @@ func (o *ClockGetParams) BindRequest(r *http.Request, route *middleware.MatchedR
return nil
}
func (o *ClockGetParams) bindTimezone(rawData []string, hasKey bool, formats strfmt.Registry) error {
func (o *TimeGetParams) bindTimezone(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]

View File

@ -0,0 +1,146 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
models "github.com/elfsternberg/timeofday/models"
)
// TimeGetOKCode is the HTTP code returned for type TimeGetOK
const TimeGetOKCode int = 200
/*TimeGetOK Returns the time of day.
swagger:response timeGetOK
*/
type TimeGetOK struct {
/*
In: Body
*/
Payload *models.Timeofday `json:"body,omitempty"`
}
// NewTimeGetOK creates TimeGetOK with default headers values
func NewTimeGetOK() *TimeGetOK {
return &TimeGetOK{}
}
// WithPayload adds the payload to the time get o k response
func (o *TimeGetOK) WithPayload(payload *models.Timeofday) *TimeGetOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the time get o k response
func (o *TimeGetOK) SetPayload(payload *models.Timeofday) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TimeGetOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// TimeGetNotFoundCode is the HTTP code returned for type TimeGetNotFound
const TimeGetNotFoundCode int = 404
/*TimeGetNotFound Time zone not found
swagger:response timeGetNotFound
*/
type TimeGetNotFound struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewTimeGetNotFound creates TimeGetNotFound with default headers values
func NewTimeGetNotFound() *TimeGetNotFound {
return &TimeGetNotFound{}
}
// WithPayload adds the payload to the time get not found response
func (o *TimeGetNotFound) WithPayload(payload *models.ErrorResponse) *TimeGetNotFound {
o.Payload = payload
return o
}
// SetPayload sets the payload to the time get not found response
func (o *TimeGetNotFound) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TimeGetNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(404)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// TimeGetInternalServerErrorCode is the HTTP code returned for type TimeGetInternalServerError
const TimeGetInternalServerErrorCode int = 500
/*TimeGetInternalServerError Something has gone horribly wrong
swagger:response timeGetInternalServerError
*/
type TimeGetInternalServerError struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewTimeGetInternalServerError creates TimeGetInternalServerError with default headers values
func NewTimeGetInternalServerError() *TimeGetInternalServerError {
return &TimeGetInternalServerError{}
}
// WithPayload adds the payload to the time get internal server error response
func (o *TimeGetInternalServerError) WithPayload(payload *models.ErrorResponse) *TimeGetInternalServerError {
o.Payload = payload
return o
}
// SetPayload sets the payload to the time get internal server error response
func (o *TimeGetInternalServerError) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TimeGetInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(500)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@ -11,8 +11,8 @@ import (
golangswaggerpaths "path"
)
// ClockGetURL generates an URL for the clock get operation
type ClockGetURL struct {
// TimeGetURL generates an URL for the time get operation
type TimeGetURL struct {
Timezone *string
_basePath string
@ -23,7 +23,7 @@ type ClockGetURL struct {
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *ClockGetURL) WithBasePath(bp string) *ClockGetURL {
func (o *TimeGetURL) WithBasePath(bp string) *TimeGetURL {
o.SetBasePath(bp)
return o
}
@ -31,12 +31,12 @@ func (o *ClockGetURL) WithBasePath(bp string) *ClockGetURL {
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *ClockGetURL) SetBasePath(bp string) {
func (o *TimeGetURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *ClockGetURL) Build() (*url.URL, error) {
func (o *TimeGetURL) Build() (*url.URL, error) {
var result url.URL
var _path = "/time"
@ -63,7 +63,7 @@ func (o *ClockGetURL) Build() (*url.URL, error) {
}
// Must is a helper function to panic when the url builder returns an error
func (o *ClockGetURL) Must(u *url.URL, err error) *url.URL {
func (o *TimeGetURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
@ -74,17 +74,17 @@ func (o *ClockGetURL) Must(u *url.URL, err error) *url.URL {
}
// String returns the string representation of the path with query string
func (o *ClockGetURL) String() string {
func (o *TimeGetURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *ClockGetURL) BuildFull(scheme, host string) (*url.URL, error) {
func (o *TimeGetURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on ClockGetURL")
return nil, errors.New("scheme is required for a full url on TimeGetURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on ClockGetURL")
return nil, errors.New("host is required for a full url on TimeGetURL")
}
base, err := o.Build()
@ -98,6 +98,6 @@ func (o *ClockGetURL) BuildFull(scheme, host string) (*url.URL, error) {
}
// StringFull returns the string representation of a complete url
func (o *ClockGetURL) StringFull(scheme, host string) string {
func (o *TimeGetURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@ -11,40 +11,40 @@ import (
middleware "github.com/go-openapi/runtime/middleware"
)
// ClockGetHandlerFunc turns a function with the right signature into a clock get handler
type ClockGetHandlerFunc func(ClockGetParams) middleware.Responder
// TimePostHandlerFunc turns a function with the right signature into a time post handler
type TimePostHandlerFunc func(TimePostParams) middleware.Responder
// Handle executing the request and returning a response
func (fn ClockGetHandlerFunc) Handle(params ClockGetParams) middleware.Responder {
func (fn TimePostHandlerFunc) Handle(params TimePostParams) middleware.Responder {
return fn(params)
}
// ClockGetHandler interface for that can handle valid clock get params
type ClockGetHandler interface {
Handle(ClockGetParams) middleware.Responder
// TimePostHandler interface for that can handle valid time post params
type TimePostHandler interface {
Handle(TimePostParams) middleware.Responder
}
// NewClockGet creates a new http.Handler for the clock get operation
func NewClockGet(ctx *middleware.Context, handler ClockGetHandler) *ClockGet {
return &ClockGet{Context: ctx, Handler: handler}
// NewTimePost creates a new http.Handler for the time post operation
func NewTimePost(ctx *middleware.Context, handler TimePostHandler) *TimePost {
return &TimePost{Context: ctx, Handler: handler}
}
/*ClockGet swagger:route GET /time clockGet
/*TimePost swagger:route POST /time timePost
Returns time of day.
*/
type ClockGet struct {
type TimePost struct {
Context *middleware.Context
Handler ClockGetHandler
Handler TimePostHandler
}
func (o *ClockGet) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
func (o *TimePost) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
var Params = NewClockGetParams()
var Params = NewTimePostParams()
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)

View File

@ -15,18 +15,18 @@ import (
models "github.com/elfsternberg/timeofday/models"
)
// NewClockPostParams creates a new ClockPostParams object
// NewTimePostParams creates a new TimePostParams object
// no default values defined in spec.
func NewClockPostParams() ClockPostParams {
func NewTimePostParams() TimePostParams {
return ClockPostParams{}
return TimePostParams{}
}
// ClockPostParams contains all the bound params for the clock post operation
// TimePostParams contains all the bound params for the time post operation
// typically these are obtained from a http.Request
//
// swagger:parameters ClockPost
type ClockPostParams struct {
// swagger:parameters TimePost
type TimePostParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
@ -40,8 +40,8 @@ type ClockPostParams struct {
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewClockPostParams() beforehand.
func (o *ClockPostParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
// To ensure default values, the struct must have been initialized with NewTimePostParams() beforehand.
func (o *TimePostParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r

View File

@ -0,0 +1,146 @@
// Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
models "github.com/elfsternberg/timeofday/models"
)
// TimePostOKCode is the HTTP code returned for type TimePostOK
const TimePostOKCode int = 200
/*TimePostOK Returns the time of day.
swagger:response timePostOK
*/
type TimePostOK struct {
/*
In: Body
*/
Payload *models.Timeofday `json:"body,omitempty"`
}
// NewTimePostOK creates TimePostOK with default headers values
func NewTimePostOK() *TimePostOK {
return &TimePostOK{}
}
// WithPayload adds the payload to the time post o k response
func (o *TimePostOK) WithPayload(payload *models.Timeofday) *TimePostOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the time post o k response
func (o *TimePostOK) SetPayload(payload *models.Timeofday) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TimePostOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// TimePostNotFoundCode is the HTTP code returned for type TimePostNotFound
const TimePostNotFoundCode int = 404
/*TimePostNotFound Time zone not found
swagger:response timePostNotFound
*/
type TimePostNotFound struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewTimePostNotFound creates TimePostNotFound with default headers values
func NewTimePostNotFound() *TimePostNotFound {
return &TimePostNotFound{}
}
// WithPayload adds the payload to the time post not found response
func (o *TimePostNotFound) WithPayload(payload *models.ErrorResponse) *TimePostNotFound {
o.Payload = payload
return o
}
// SetPayload sets the payload to the time post not found response
func (o *TimePostNotFound) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TimePostNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(404)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// TimePostInternalServerErrorCode is the HTTP code returned for type TimePostInternalServerError
const TimePostInternalServerErrorCode int = 500
/*TimePostInternalServerError Something has gone horribly wrong
swagger:response timePostInternalServerError
*/
type TimePostInternalServerError struct {
/*
In: Body
*/
Payload *models.ErrorResponse `json:"body,omitempty"`
}
// NewTimePostInternalServerError creates TimePostInternalServerError with default headers values
func NewTimePostInternalServerError() *TimePostInternalServerError {
return &TimePostInternalServerError{}
}
// WithPayload adds the payload to the time post internal server error response
func (o *TimePostInternalServerError) WithPayload(payload *models.ErrorResponse) *TimePostInternalServerError {
o.Payload = payload
return o
}
// SetPayload sets the payload to the time post internal server error response
func (o *TimePostInternalServerError) SetPayload(payload *models.ErrorResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TimePostInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(500)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@ -11,15 +11,15 @@ import (
golangswaggerpaths "path"
)
// ClockPostURL generates an URL for the clock post operation
type ClockPostURL struct {
// TimePostURL generates an URL for the time post operation
type TimePostURL struct {
_basePath string
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *ClockPostURL) WithBasePath(bp string) *ClockPostURL {
func (o *TimePostURL) WithBasePath(bp string) *TimePostURL {
o.SetBasePath(bp)
return o
}
@ -27,12 +27,12 @@ func (o *ClockPostURL) WithBasePath(bp string) *ClockPostURL {
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *ClockPostURL) SetBasePath(bp string) {
func (o *TimePostURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *ClockPostURL) Build() (*url.URL, error) {
func (o *TimePostURL) Build() (*url.URL, error) {
var result url.URL
var _path = "/time"
@ -47,7 +47,7 @@ func (o *ClockPostURL) Build() (*url.URL, error) {
}
// Must is a helper function to panic when the url builder returns an error
func (o *ClockPostURL) Must(u *url.URL, err error) *url.URL {
func (o *TimePostURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
@ -58,17 +58,17 @@ func (o *ClockPostURL) Must(u *url.URL, err error) *url.URL {
}
// String returns the string representation of the path with query string
func (o *ClockPostURL) String() string {
func (o *TimePostURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *ClockPostURL) BuildFull(scheme, host string) (*url.URL, error) {
func (o *TimePostURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on ClockPostURL")
return nil, errors.New("scheme is required for a full url on TimePostURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on ClockPostURL")
return nil, errors.New("host is required for a full url on TimePostURL")
}
base, err := o.Build()
@ -82,6 +82,6 @@ func (o *ClockPostURL) BuildFull(scheme, host string) (*url.URL, error) {
}
// StringFull returns the string representation of a complete url
func (o *ClockPostURL) StringFull(scheme, host string) string {
func (o *TimePostURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@ -37,11 +37,11 @@ func NewTimeofdayAPI(spec *loads.Document) *TimeofdayAPI {
BearerAuthenticator: security.BearerAuth,
JSONConsumer: runtime.JSONConsumer(),
JSONProducer: runtime.JSONProducer(),
ClockGetHandler: ClockGetHandlerFunc(func(params ClockGetParams) middleware.Responder {
return middleware.NotImplemented("operation ClockGet has not yet been implemented")
TimeGetHandler: TimeGetHandlerFunc(func(params TimeGetParams) middleware.Responder {
return middleware.NotImplemented("operation TimeGet has not yet been implemented")
}),
ClockPostHandler: ClockPostHandlerFunc(func(params ClockPostParams) middleware.Responder {
return middleware.NotImplemented("operation ClockPost has not yet been implemented")
TimePostHandler: TimePostHandlerFunc(func(params TimePostParams) middleware.Responder {
return middleware.NotImplemented("operation TimePost has not yet been implemented")
}),
}
}
@ -74,10 +74,10 @@ type TimeofdayAPI struct {
// JSONProducer registers a producer for a "application/json" mime type
JSONProducer runtime.Producer
// ClockGetHandler sets the operation handler for the clock get operation
ClockGetHandler ClockGetHandler
// ClockPostHandler sets the operation handler for the clock post operation
ClockPostHandler ClockPostHandler
// TimeGetHandler sets the operation handler for the time get operation
TimeGetHandler TimeGetHandler
// TimePostHandler sets the operation handler for the time post operation
TimePostHandler TimePostHandler
// ServeError is called when an error is received, there is a default handler
// but you can set your own with this
@ -141,12 +141,12 @@ func (o *TimeofdayAPI) Validate() error {
unregistered = append(unregistered, "JSONProducer")
}
if o.ClockGetHandler == nil {
unregistered = append(unregistered, "ClockGetHandler")
if o.TimeGetHandler == nil {
unregistered = append(unregistered, "TimeGetHandler")
}
if o.ClockPostHandler == nil {
unregistered = append(unregistered, "ClockPostHandler")
if o.TimePostHandler == nil {
unregistered = append(unregistered, "TimePostHandler")
}
if len(unregistered) > 0 {
@ -250,12 +250,12 @@ func (o *TimeofdayAPI) initHandlerCache() {
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/time"] = NewClockGet(o.context, o.ClockGetHandler)
o.handlers["GET"]["/time"] = NewTimeGet(o.context, o.TimeGetHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/time"] = NewClockPost(o.context, o.ClockPostHandler)
o.handlers["POST"]["/time"] = NewTimePost(o.context, o.TimePostHandler)
}

74
timeofday/handlers.go Normal file
View File

@ -0,0 +1,74 @@
package timeofday
import(
"time"
"errors"
"fmt"
middleware "github.com/go-openapi/runtime/middleware"
"github.com/elfsternberg/timeofday/restapi/operations"
"github.com/elfsternberg/timeofday/models"
"github.com/go-openapi/swag"
)
func getTimeOfDay(tz *string) (*string, error) {
t := time.Now()
utc, err := time.LoadLocation(*tz)
if err != nil {
return nil, errors.New(fmt.Sprintf("Time zone not found: %s", *tz))
}
thetime := t.In(utc).String()
return &thetime, nil
}
func GetTime(timezone *Timezone) func(operations.TimeGetParams) middleware.Responder{
defaultTZ := timezone.Timezone
return func(params operations.TimeGetParams) middleware.Responder {
var tz *string = &defaultTZ
if (params.Timezone != nil) {
tz = params.Timezone
}
thetime, err := getTimeOfDay(tz)
if err != nil {
return operations.NewTimeGetNotFound().WithPayload(
&models.ErrorResponse {
int32(operations.TimeGetNotFoundCode),
swag.String(fmt.Sprintf("%s", err)),
})
}
return operations.NewTimeGetOK().WithPayload(
&models.Timeofday{
Timeofday: *thetime,
})
}
}
func PostTime(timezone *Timezone) func(operations.TimePostParams) middleware.Responder{
defaultTZ := timezone.Timezone
return func(params operations.TimePostParams) middleware.Responder {
var tz *string = &defaultTZ
if (params.Timezone != nil) {
tz = params.Timezone.Timezone
}
thetime, err := getTimeOfDay(tz)
if err != nil {
return operations.NewTimePostNotFound().WithPayload(
&models.ErrorResponse {
int32(operations.TimePostNotFoundCode),
swag.String(fmt.Sprintf("%s", err)),
})
}
return operations.NewTimePostOK().WithPayload(
&models.Timeofday{
Timeofday: *thetime,
})
}
}

View File

@ -1,76 +0,0 @@
package timeofday
import(
"time"
"errors"
"fmt"
middleware "github.com/go-openapi/runtime/middleware"
"github.com/elfsternberg/timeofday/restapi/operations"
"github.com/elfsternberg/timeofday/models"
"github.com/go-openapi/swag"
)
func getTimeOfDay(tz *string) (*string, error) {
defaultTZ := "UTC"
t := time.Now()
if tz == nil {
tz = &defaultTZ
}
utc, err := time.LoadLocation(*tz)
if err != nil {
return nil, errors.New(fmt.Sprintf("Time zone not found: %s", *tz))
}
thetime := t.In(utc).String()
return &thetime, nil
}
func GetClock(params operations.ClockGetParams) middleware.Responder {
var tz *string = nil
if (params.Timezone != nil) {
tz = params.Timezone
}
thetime, err := getTimeOfDay(tz)
if err != nil {
return operations.NewClockGetNotFound().WithPayload(
&models.ErrorResponse {
int32(operations.ClockGetNotFoundCode),
swag.String(fmt.Sprintf("%s", err)),
})
}
return operations.NewClockGetOK().WithPayload(
&models.Timeofday{
Timeofday: *thetime,
})
}
func PostClock(params operations.ClockPostParams) middleware.Responder {
var tz *string = nil
if (params.Timezone != nil) {
tz = params.Timezone.Timezone
}
thetime, err := getTimeOfDay(tz)
if err != nil {
return operations.NewClockPostNotFound().WithPayload(
&models.ErrorResponse {
int32(operations.ClockPostNotFoundCode),
swag.String(fmt.Sprintf("%s", err)),
})
}
return operations.NewClockPostOK().WithPayload(
&models.Timeofday{
Timeofday: *thetime,
})
}

5
timeofday/timezone.go Normal file
View File

@ -0,0 +1,5 @@
package timeofday
type Timezone struct {
Timezone string `long:"timezone" short:"t" description:"The default time zone" env:"GOTIME_DEFAULT_TIMEZONE" default:"UTC"`
}