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

Initial updates #1

Merged
merged 8 commits into from
Oct 14, 2024
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
16 changes: 7 additions & 9 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
### CODE OF CONDUCT
# CODE OF CONDUCT
Evernorth Strategic Development, Inc. (“Evernorth”) welcomes contributions to our hosted open source projects. We have adopted this Code of Conduct (the “Code”) to facilitate your participation and to ensure our open source community remains a safe, harassment-free, and collaborative space.

# Scope
## Scope
This Code applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.

# Our Standards
## Our Standards
We strive to make participation in our open source projects open and enjoyable for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex, gender identity, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual orientation.

Examples of behavior that contributes to a positive environment for our community include:
Expand All @@ -21,15 +21,13 @@ Examples of unacceptable behavior include:
* Publishing others’ private information, such as a physical or email address, without their explicit permission.
* Other conduct which could reasonably be considered inappropriate in a professional setting.

# Enforcement
## Enforcement
The Evernorth Open Source Leadership Group (the “Leadership Group”) is responsible for clarifying and enforcing this Code and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
The Leadership Group has the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code, and will communicate reasons for moderation decisions when appropriate.

# Reporting
## Reporting
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the Leadership Group at [[email protected]](mailto:[email protected]). All complaints will be reviewed and investigated promptly and fairly, while respecting the privacy and security of the reporter. We will determine if and what response is appropriate, and every matter may not result in a direct response from us.
Consequences for inappropriate behavior may include: (1) a warning with consequences for continued behavior; (2) restricted or suspended access to certain projects or other community members for a specific period of time; (3) temporary suspensions from participation in the community; and (4) permanent bans from participating in the community. Factors that may be considered when imposing various consequences may include, but are not limited to, the seriousness or nature of the harm caused, repeated violations of this Code, and the impact of the activity on our broader open source community.

# Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org), version 2.0, available at [contributor-covenant.org/version/2/0/](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).


## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org), version 2.0, available at [contributor-covenant.org/version/2/0/](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).
139 changes: 74 additions & 65 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,93 +1,102 @@
# http-problemdetails-go

An implementation of [IETF RFC 9457 Problem Details for HTTP APIs](https://www.rfc-editor.org/rfc/rfc9457.html) which is a specification for a standard error structure for HTTP APIs.


## Dependencies
See the [go.mod](go.mod) file.

## Building from Source

Detailed instructions on how to build the project from source. Also note where to get pre-built distribution, if building is not required.

## Installation
```go get -u github.com/Evernorth/http-problemdetails-go```

## Features
- The MIME type of the response is `application/problem+json`.
- Supports the following HTTP status codes:

| HTTP Code | Method |
|-------------------------------------|-------------------------------------------------|
| 400 Bad Request | [`NewBadRequest()`](problemdetails.go) |
| 401 Unauthorized | [`NewUnauthorized()`](problemdetails.go) |
| 403 Forbidden | [`NewForbidden()`](problemdetails.go) |
| 404 Not Found | [`NewNotFound()`](problemdetails.go) |
| 409 Conflict | [`NewConflict()`](problemdetails.go) |
| 429 Too Many Requests | [`NewTooManyRequests()`](problemdetails.go) |
| 500 Internal Server Error | [`NewInternalServerError()`](problemdetails.go) |
| 501 Not Implemented | [`NewNotImplemented()`](problemdetails.go) |
| 502 Bad Gateway | [`NewBadGateway()`](problemdetails.go) |
| 503 Service Unavailable | [`NewServiceUnavailable()`](problemdetails.go) |
| 504 Gateway Timeout | [`NewGatewayTimeout()`](problemdetails.go) |


>Note: MIME type must be set in the response header to comply with the RFC 9457 specification.
| HTTP Code | Method |
|---------------------------|----------------------------------------------------------------|
| 400 Bad Request | [`NewBadRequest()`](problemdetails/problemdetails.go) |
| 401 Unauthorized | [`NewUnauthorized()`](problemdetails/problemdetails.go) |
| 403 Forbidden | [`NewForbidden()`](problemdetails/problemdetails.go) |
| 404 Not Found | [`NewNotFound()`](problemdetails/problemdetails.go) |
| 405 Method Not Allowed | [`NewMethodNotAllowed()`](problemdetails/problemdetails.go) |
| 409 Conflict | [`NewConflict()`](problemdetails/problemdetails.go) |
| 429 Too Many Requests | [`NewTooManyRequests()`](problemdetails/problemdetails.go) |
| 500 Internal Server Error | [`NewInternalServerError()`](problemdetails/problemdetails.go) |
| 502 Bad Gateway | [`NewBadGateway()`](problemdetails/problemdetails.go) |
| 503 Service Unavailable | [`NewServiceUnavailable()`](problemdetails/problemdetails.go) |
| 504 Gateway Timeout | [`NewGatewayTimeout()`](problemdetails/problemdetails.go) |

>Note: MIME type must be set in the response header to comply with the RFC 9457 specification. The MimeType constant is provided for this purpose.

## Usage
### Creating a simple HTTP ProblemDetails
The example code below demonstrates how to create simple ProblemDetails instances as well as how to add information to them using the With* functions.

You can create a ProblemDetails instance by simply calling functions like `problemdetails.NewInternalServerError()`, `problemdetails.NewNotFound()` and `problemdetails.NewBadRequest()`.

You can easily override the default ProblemDetails title and detail fields and provide custom extension fields by using the `WithTitle`, `WithDetail` and `WithExtension` functions.
```
package main

import (
"github.com/Evernorth/http-problemdetails-go/problemdetails"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"net/http"
"fmt"
"github.com/Evernorth/http-problemdetails-go/problemdetails"
"github.com/go-chi/render"
"net/http"
)

func getSomething(httpRespWriter http.ResponseWriter, httpReq *http.Request) {

err := doSomething()
if err != nil {
httpRespWriter.WriteHeader(http.StatusInternalServerError)
render.JSON(httpRespWriter, httpReq, problemdetails.NewInternalServerError())
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
return
}
...
func handler(httpRespWriter http.ResponseWriter, httpReq *http.Request) {

// If the request is not a GET, return a 405 Method Not Allowed
if httpReq.Method != http.MethodGet {
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusMethodNotAllowed)
render.JSON(httpRespWriter, httpReq, problemdetails.NewMethodNotAllowed())
return
}

// Get the example-type from the query parameters
queryParams := httpReq.URL.Query()
exampleType := queryParams.Get("example-type")

if exampleType == "basic" {

// Return a 500 Internal Server Error, using the NewInternalServerError function.
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusInternalServerError)
render.JSON(httpRespWriter, httpReq, problemdetails.NewInternalServerError())

} else if exampleType == "advanced" {

// Return a 500 Internal Server Error, using the NewInternalServerError and With* functions.
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusInternalServerError)
render.JSON(httpRespWriter, httpReq, problemdetails.NewInternalServerError().
WithTitle("KABOOM!!!").
WithDetail("The unthinkable has occurred.").
WithExtension("example1", "test").
WithExtension("example2", "this could be a struct if you like"))

} else {

// Return a 400 Bad Request, using the NewBadRequest function.
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusBadRequest)
render.JSON(httpRespWriter, httpReq, problemdetails.NewBadRequest().
WithDetail("example-type must be basic or advanced."))

}
}
```
### Creating a complex HTTP ProblemDetails
You can easily override the default ProblemDetails title and detail fields and provide custom extension fields by using the `WithTitle`, `WithDetail` and `WithExtension` functions.
```
package main

import (
"github.com/Evernorth/http-problemdetails-go/problemdetails"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"net/http"
)
func main() {
http.HandleFunc("/", handler)

func getSomething(httpRespWriter http.ResponseWriter, httpReq *http.Request) {

err := doSomething()
if err != nil {
httpRespWriter.WriteHeader(http.StatusInternalServerError)
render.JSON(httpRespWriter, httpReq, problemdetails.NewInternalServerError().WithTitle(
"KABOOM!!!").WithDetail("The unthinkable has occurred.").WithExtension(
"example1", "test").WithExtension(
"example2", "this could be a struct if you like"))
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)

return
}
...
fmt.Println("Starting server on 8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Server failed to start:", err)
}
}
```

## Dependencies
See the [go.mod](go.mod) file.

## Support
If you have questions, concerns, bug reports, etc. See [CONTRIBUTING](CONTRIBUTING.md).

Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
module github.com/Evernorth/problemdetails
module github.com/Evernorth/http-problemdetails-go

go 1.23.1

require (
github.com/go-chi/render v1.0.3
github.com/google/uuid v1.6.0
github.com/stretchr/testify v1.9.0
)

require (
github.com/ajg/form v1.5.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
25 changes: 0 additions & 25 deletions internal/examples/advanced-example.go

This file was deleted.

23 changes: 0 additions & 23 deletions internal/examples/basic-example.go

This file was deleted.

61 changes: 61 additions & 0 deletions internal/examples/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"fmt"
"github.com/Evernorth/http-problemdetails-go/problemdetails"
"github.com/go-chi/render"
"net/http"
)

func handler(httpRespWriter http.ResponseWriter, httpReq *http.Request) {

// If the request is not a GET, return a 405 Method Not Allowed
if httpReq.Method != http.MethodGet {
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusMethodNotAllowed)
render.JSON(httpRespWriter, httpReq, problemdetails.NewMethodNotAllowed())
return
}

// Get the example-type from the query parameters
queryParams := httpReq.URL.Query()
exampleType := queryParams.Get("example-type")

if exampleType == "basic" {

// Return a 500 Internal Server Error, using the NewInternalServerError function.
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusInternalServerError)
render.JSON(httpRespWriter, httpReq, problemdetails.NewInternalServerError())

} else if exampleType == "advanced" {

// Return a 500 Internal Server Error, using the NewInternalServerError and With* functions.
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusInternalServerError)
render.JSON(httpRespWriter, httpReq, problemdetails.NewInternalServerError().
WithTitle("KABOOM!!!").
WithDetail("The unthinkable has occurred.").
WithExtension("example1", "test").
WithExtension("example2", "this could be a struct if you like"))

} else {

// Return a 400 Bad Request, using the NewBadRequest function.
httpRespWriter.Header().Set("Content-Type", problemdetails.MimeType)
httpRespWriter.WriteHeader(http.StatusBadRequest)
render.JSON(httpRespWriter, httpReq, problemdetails.NewBadRequest().
WithDetail("example-type must be basic or advanced."))

}
}

func main() {
http.HandleFunc("/", handler)

fmt.Println("Starting server on 8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Server failed to start:", err)
}
}
3 changes: 0 additions & 3 deletions internal/examples/go.mod

This file was deleted.

Loading