Skip to content

Commit

Permalink
Config custom origin allowed
Browse files Browse the repository at this point in the history
  • Loading branch information
prongbang committed May 12, 2023
1 parent 73e2c69 commit 0cf5358
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ services:
- "8000:8000"
volumes:
- "./mock:/mock"
environment:
- ORIGIN_ALLOWED=http://localhost:9000
```

```
Expand Down
11 changes: 9 additions & 2 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import (
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/prongbang/wiremock/v2/pkg/config"
"github.com/prongbang/wiremock/v2/pkg/core"
"github.com/prongbang/wiremock/v2/pkg/status"
"log"
"net/http"
"os"
)

type API interface {
Expand All @@ -23,8 +25,13 @@ func (a *api) Register(cfg config.Config) {

r := mux.NewRouter()
headers := handlers.AllowedHeaders([]string{"*"})
methods := handlers.AllowedMethods([]string{http.MethodGet, http.MethodPost, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodTrace, http.MethodDelete, http.MethodOptions})
origins := handlers.AllowedOrigins([]string{"*"})
methods := handlers.AllowedMethods([]string{http.MethodGet, http.MethodPost, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodTrace, http.MethodDelete, http.MethodOptions, http.MethodConnect})
originsAllowed := os.Getenv("ORIGIN_ALLOWED")
allowedOrigins := []string{"*"}
if originsAllowed != "" {
allowedOrigins = append(allowedOrigins, core.ParseOrigins(originsAllowed)...)
}
origins := handlers.AllowedOrigins(allowedOrigins)

// Router
a.Router.Initials(r)
Expand Down
13 changes: 13 additions & 0 deletions pkg/core/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package core
import (
"encoding/json"
"net/http"
"strings"
)

func Body(r *http.Request) map[string]interface{} {
Expand Down Expand Up @@ -59,3 +60,15 @@ func BindCaseBody(mockBody map[string]interface{}, r *http.Request) map[string]i
}
return data
}

func ParseOrigins(originAllowed string) []string {
origins := []string{}
if originAllowed != "" {
originList := strings.Split(originAllowed, ",")
for _, origin := range originList {
trimmedOrigin := strings.TrimSpace(origin)
origins = append(origins, trimmedOrigin)
}
}
return origins
}

0 comments on commit 0cf5358

Please sign in to comment.