| 1 | import ( |
| 2 | "github.com/perimeterx/perimeterx-go-sdk/perimeterx" |
| 3 | ) |
| 4 | |
| 5 | type Adapter func(http.Handler) http.Handler |
| 6 | |
| 7 | var pxConfig perimeterx.PxConfig |
| 8 | |
| 9 | func main() { |
| 10 | log.Printf("Go Server is running on port %d, %s OS with an %s CPU.", port, goruntime.GOOS, goruntime.GOARCH) |
| 11 | |
| 12 | pxConfig = *NewPXConfigBuilder("App ID", "Cookie Secret", "Auth Token"). |
| 13 | SetMonitorMode("active_blocking"). |
| 14 | Build() |
| 15 | |
| 16 | http.Handle("/", middleware()(http.FileServer(http.Dir("./static")))) |
| 17 | http.ListenAndServe(":3000", nil) |
| 18 | } |
| 19 | |
| 20 | func middleware() Adapter { |
| 21 | return func(h http.Handler) http.Handler { |
| 22 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 23 | responseWriter := perimeterx.NewResponseWriterWrapper(w) |
| 24 | response, context, err := perimeterx.Enforce(r, &ExampleRuntime{}) |
| 25 | |
| 26 | fmt.Print(context.Score) |
| 27 | |
| 28 | if err != nil { |
| 29 | fmt.Print(err) |
| 30 | } |
| 31 | |
| 32 | if response.Body != nil { |
| 33 | responseWriter.WriteHeader(response.StatusCode) |
| 34 | responseWriter.Header().Set("Content-Type", response.Header.Get("Content-Type")) |
| 35 | var body, _ = ioutil.ReadAll(response.Body) |
| 36 | responseWriter.Write(body) |
| 37 | } else { |
| 38 | h.ServeHTTP(responseWriter, r) |
| 39 | } |
| 40 | }) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | var tr = &http.Transport{ |
| 45 | MaxIdleConnsPerHost: 10, |
| 46 | ResponseHeaderTimeout: 60 * time.Second, |
| 47 | } |
| 48 | var client = &http.Client{Transport: tr} |
| 49 | |
| 50 | type ExampleRuntime struct { |
| 51 | } |
| 52 | |
| 53 | func (runtime *ExampleRuntime) GetConfig() perimeterx.PxConfig { |
| 54 | return pxConfig |
| 55 | } |
| 56 | |
| 57 | func (runtime *ExampleRuntime) PerformSyncRequest(req *http.Request, timeout int) (*http.Response, error) { |
| 58 | client.Timeout = time.Duration(timeout) * time.Millisecond |
| 59 | return client.Do(req) |
| 60 | } |
| 61 | |
| 62 | func (runtime *ExampleRuntime) PerformAsyncRequest(req *http.Request, timeout int) { |
| 63 | go runtime.PerformSyncRequest(req, timeout) |
| 64 | } |
| 65 | |
| 66 | func (runtime *ExampleRuntime) GetOS() string { |
| 67 | return goruntime.GOOS |
| 68 | } |
| 69 | |
| 70 | func (runtime *ExampleRuntime) GetHostName() string { |
| 71 | osName, _ := os.Hostname() |
| 72 | return osName |
| 73 | } |
| 74 | |
| 75 | func (runtime *ExampleRuntime) Log(message string) { |
| 76 | fmt.Print(message) |
| 77 | } |