Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formats with gofmt #11

Merged
merged 1 commit into from
Nov 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions app/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
)

type Environment struct {
Ip string
Port int
Addr string
Ip string
Port int
Addr string
Domain string

OpenAPI oas.Openapi
Expand Down
93 changes: 47 additions & 46 deletions endpoint/docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ import (

"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

"github.com/charmixer/oas/api"
"github.com/charmixer/golang-api-template/app"
"github.com/charmixer/oas/api"

"github.com/charmixer/golang-api-template/endpoint"

"github.com/rs/zerolog/log"
)

type GetDocsRequest struct {}
type GetDocsRequest struct{}
type GetDocsEndpoint struct {
endpoint.Endpoint
}

func (ep *GetDocsEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
url := fmt.Sprintf("http://%s:%d/docs/openapi?format=json", app.Env.Domain, app.Env.Port)

Expand Down Expand Up @@ -53,44 +54,44 @@ func (ep *GetDocsEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
panic(err)
}

/* w.Write([]byte(fmt.Sprintf(`
<!doctype html> <!-- Important: must specify -->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;600&family=Roboto+Mono&display=swap" rel="stylesheet">
</head>
<body>

<rapi-doc
id="rapidoc-container"
theme = "dark"
layout = "row"
render-style = "read"
show-header = "false"
allow-try = "false"
allow-server-selection = "false"
allow-authentication="false"

regular-font="Open Sans"
mono-font="Roboto Mono"
> </rapi-doc>

<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {

let docEl = document.getElementById("rapidoc-container");

let objSpec = JSON.parse(` + "`%s`" + `);
docEl.loadSpec(objSpec);
})
</script>

</body>
</html>
`, spec)))*/
/* w.Write([]byte(fmt.Sprintf(`
<!doctype html> <!-- Important: must specify -->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;600&family=Roboto+Mono&display=swap" rel="stylesheet">
</head>
<body>

<rapi-doc
id="rapidoc-container"
theme = "dark"
layout = "row"
render-style = "read"
show-header = "false"
allow-try = "false"
allow-server-selection = "false"
allow-authentication="false"

regular-font="Open Sans"
mono-font="Roboto Mono"
> </rapi-doc>

<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {

let docEl = document.getElementById("rapidoc-container");

let objSpec = JSON.parse(` + "`%s`" + `);
docEl.loadSpec(objSpec);
})
</script>

</body>
</html>
`, spec)))*/

w.Write([]byte(fmt.Sprintf(`
<!doctype html> <!-- Important: must specify -->
Expand All @@ -109,7 +110,7 @@ func (ep *GetDocsEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hideDownloadButton: true
};

Redoc.init(JSON.parse(` + "`%s`" + `), options, document.getElementById('redoc-container'))
Redoc.init(JSON.parse(`+"`%s`"+`), options, document.getElementById('redoc-container'))
})
</script>

Expand All @@ -118,23 +119,23 @@ func (ep *GetDocsEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
`, spec)))
}

func NewGetDocsEndpoint() (endpoint.EndpointHandler) {
func NewGetDocsEndpoint() endpoint.EndpointHandler {
ep := GetDocsEndpoint{}

ep.Setup(
endpoint.WithSpecification(api.Path{
Summary: "OpenAPI documentation",
Summary: "OpenAPI documentation",
Description: ``,
Tags: OPENAPI_TAGS,
Tags: OPENAPI_TAGS,

Request: api.Request{
Description: ``,
Schema: GetDocsRequest{},
Schema: GetDocsRequest{},
},

Responses: []api.Response{{
Description: `OpenAPI documentation rendered in HTML`,
Code: 200,
Code: 200,
ContentType: []string{"text/html"},
//Schema: GetHealthResponse{},
}},
Expand Down
23 changes: 12 additions & 11 deletions endpoint/docs/openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import (
"fmt"
"net/http"

"github.com/charmixer/golang-api-template/app"
"github.com/charmixer/oas/api"
"github.com/charmixer/oas/exporter"
"github.com/charmixer/golang-api-template/app"

"github.com/charmixer/golang-api-template/endpoint"
"github.com/charmixer/golang-api-template/endpoint/problem"
Expand All @@ -18,7 +18,7 @@ import (

var (
OPENAPI_TAGS = []api.Tag{
{Name: "Documentation", Description:""},
{Name: "Documentation", Description: ""},
}
)

Expand All @@ -31,6 +31,7 @@ type GetOpenapiResponse exporter.Openapi
type GetOpenapiEndpoint struct {
endpoint.Endpoint
}

func (ep GetOpenapiEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
tr := otel.Tracer("request")
Expand All @@ -46,10 +47,10 @@ func (ep GetOpenapiEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
response := app.Env.OpenAPI

responseType := ""
if request.Format == "json" {
if request.Format == "json" {
w.Header().Set("Content-Type", "application/json")
responseType = "json"
} else {
} else {
w.Header().Set("Content-Type", "text/plain; application/yaml; charset=utf-8")
responseType = "yaml"
}
Expand All @@ -60,26 +61,26 @@ func (ep GetOpenapiEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}

func NewGetOpenapiEndpoint() (endpoint.EndpointHandler) {
func NewGetOpenapiEndpoint() endpoint.EndpointHandler {
ep := GetOpenapiEndpoint{}

ep.Setup(
endpoint.WithSpecification(api.Path{
Summary: "OpenAPI specification",
Summary: "OpenAPI specification",
Description: ``,
Tags: OPENAPI_TAGS,
Tags: OPENAPI_TAGS,

Request: api.Request{
Description: ``,
Schema: GetOpenapiRequest{},
Schema: GetOpenapiRequest{},
},

Responses: []api.Response{{
Description: `Returns openapi spec in given format`,
Code: 200,
Code: 200,
ContentType: []string{"application/json", "application/yaml"},
Schema: exporter.Openapi{},
},/*{
Schema: exporter.Openapi{},
}, /*{
Description: `error ...`,
Code: 400,
ContentType: []string{"application/json"},
Expand Down
8 changes: 4 additions & 4 deletions endpoint/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package endpoint
import (
"net/http"

"github.com/charmixer/oas/api"
"github.com/charmixer/golang-api-template/middleware"
"github.com/charmixer/oas/api"
)

type EndpointHandler interface {
Expand All @@ -15,7 +15,7 @@ type EndpointHandler interface {
type Endpoint struct {
EndpointHandler
specification api.Path
middleware []middleware.MiddlewareHandler
middleware []middleware.MiddlewareHandler
}
type EndpointOption func(e *Endpoint)

Expand All @@ -25,10 +25,10 @@ func (ep *Endpoint) Setup(options ...EndpointOption) {
}
}

func (ep Endpoint) Specification() (api.Path) {
func (ep Endpoint) Specification() api.Path {
return ep.specification
}
func (ep Endpoint) Middleware() ([]middleware.MiddlewareHandler) {
func (ep Endpoint) Middleware() []middleware.MiddlewareHandler {
return ep.middleware
}

Expand Down
15 changes: 8 additions & 7 deletions endpoint/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,31 @@ import (

var (
OPENAPI_TAGS = []api.Tag{
{Name: "Metrics", Description:""},
{Name: "Metrics", Description: ""},
}
)

type GetMetricsRequest struct {}
type GetMetricsResponse struct {}
type GetMetricsRequest struct{}
type GetMetricsResponse struct{}

// https://golang.org/doc/effective_go#embedding
type GetMetricsEndpoint struct {
endpoint.Endpoint
}

func (ep GetMetricsEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t := promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}).(http.HandlerFunc)
t.ServeHTTP(w, r)
}

func NewGetMetricsEndpoint() (endpoint.EndpointHandler) {
func NewGetMetricsEndpoint() endpoint.EndpointHandler {
ep := GetMetricsEndpoint{}

ep.Setup(
endpoint.WithSpecification(api.Path{
Summary: "Get metrics from the application",
Summary: "Get metrics from the application",
Description: `Get metrics from the application`,
Tags: OPENAPI_TAGS,
Tags: OPENAPI_TAGS,

Request: api.Request{
Description: `Request metrics`,
Expand All @@ -45,7 +46,7 @@ func NewGetMetricsEndpoint() (endpoint.EndpointHandler) {

Responses: []api.Response{{
Description: `Metrics from prometheus`,
Code: 200,
Code: 200,
ContentType: []string{"application/text"},
//Schema: GetMetricsResponse{},
}},
Expand Down
4 changes: 0 additions & 4 deletions endpoint/problem/problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,6 @@ func Error(w http.ResponseWriter, msg string, status int) error {
return New(status).WithDetail(msg).Write(w)
}





// ValidationProblem is an example of extending the ProblemDetails structure
// as per the form validation example in section 3 of RFC 7807, to support
// reporting of server-side data validation errors.
Expand Down
42 changes: 21 additions & 21 deletions middleware/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,32 @@ import (
"net/http"
)

func WithContext() (MiddlewareHandler) {
return func (next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check for incoming header, use it if exists
reqID := r.Header.Get("X-Request-Id")
func WithContext() MiddlewareHandler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check for incoming header, use it if exists
reqID := r.Header.Get("X-Request-Id")

// Create request id with UUID4
if reqID == "" {
uuid4, _ := uuid.NewV4()
reqID = uuid4.String()
}
// Create request id with UUID4
if reqID == "" {
uuid4, _ := uuid.NewV4()
reqID = uuid4.String()
}

r.Header.Set("X-Request-Id", reqID)
r.Header.Set("X-Request-Id", reqID)

ctx := context.WithValue(r.Context(), "req_id", reqID)
ctx := context.WithValue(r.Context(), "req_id", reqID)

host, _, _ := net.SplitHostPort(r.RemoteAddr)
ctx = context.WithValue(ctx, "remote_ip", host)
host, _, _ := net.SplitHostPort(r.RemoteAddr)
ctx = context.WithValue(ctx, "remote_ip", host)

ua := r.Header.Get("User-Agent")
ctx = context.WithValue(ctx, "user_agent", ua)
ua := r.Header.Get("User-Agent")
ctx = context.WithValue(ctx, "user_agent", ua)

ref := r.Header.Get("Referer")
ctx = context.WithValue(ctx, "referer", ref)
ref := r.Header.Get("Referer")
ctx = context.WithValue(ctx, "referer", ref)

next.ServeHTTP(w, r.WithContext(ctx))
})
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
Loading