Skip to content
This repository has been archived by the owner on Oct 30, 2023. It is now read-only.

Commit

Permalink
feat: add api routes and multiple handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicolas Levée committed Apr 19, 2020
1 parent 2c1f8fa commit ebb79a0
Show file tree
Hide file tree
Showing 12 changed files with 334 additions and 61 deletions.
2 changes: 2 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export WOOS_KEY=woos-abcdefghijklmnop0123456789
export WOOS_DOMAIN=mondomaine.fr
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@

# Dependency directories (remove the comment below to include it)
vendor/

.env
33 changes: 27 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,46 @@ Ce script a pour objet la recherche de créneau dans les Drives Auchan.

## Usage

Pour l'identifiant de votre drive, on peut le trouver
dans les liens présent sur cette page : [Liste des drives](https://www.auchandrive.fr/drive/nos-drives/)
Pour l'identifiant de votre drive, on peut le trouver dans les liens présent sur cette page : [Liste des drives](https://www.auchandrive.fr/drive/nos-drives/)

Le script va tourné en continue et va affiché sur la console si un créneau est disponible
Si vous possédez une clé woosmap avec tous les drives vous pouvez renseigner ces informations dans un fichier .env (voir .env.dist)

Le script va tourner en continue et va afficher sur la console si un créneau est disponible

Pour lancer le scripts :

```bash
./go-auchan-drive-checker -id [ID DU DRIVE]
```

Ou si vous avez une clé woosmap, vous pouvez utiliser la recherche par code postal :

```bash
./go-auchan-drive-checker -cp [CODE POSTAL]
```

## Usage API

Pour rendre accessible la recherche de créneau via une mini API :

```bash
./go-auchan-drive-checker -id [ID DU DRIVE] -port 8089 -host 0.0.0.0
./go-auchan-drive-checker -port 8089 -host 0.0.0.0 &
```

Pour avoir la liste des clés de drive disponible :

```bash
curl 127.0.0.1:8089/stores?postalCode=[CODE POSTAL]
```

Pour ajouter un scrapper sur un store :

```bash
curl -XPUT 127.0.0.1:8089/scrappers/[ID DU DRIVE]
```

Pour tester le serveur :
Pour checké l'état d'un drive :

```bash
curl 127.0.0.1:8089/
curl 127.0.0.1:8089/scrappers/[ID DU DRIVE]
```
16 changes: 16 additions & 0 deletions internal/api/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package api

import (
"log"
"net/http"

"github.com/gorilla/mux"
)

// StartServer demarrage du server
func StartServer(host string, port string) {
r := mux.NewRouter()
addStoreRoutes(r)
addScrapperRoutes(r)
log.Fatal(http.ListenAndServe(host+":"+port, r))
}
40 changes: 40 additions & 0 deletions internal/api/scrappers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package api

import (
"encoding/json"
"log"
"net/http"

"github.com/gorilla/mux"
"github.com/nlevee/go-auchan-drive-checker/pkg/auchan"
)

// AddScrapperRoutes populate router
func addScrapperRoutes(r *mux.Router) {
// ajoute un scrapper sur le store : storeid
r.HandleFunc("/scrappers/{storeid}", addScrapper).Methods(http.MethodPut)
// récupère l'état du scrapper sur le store : storeid
r.HandleFunc("/scrappers/{storeid}", getScrapperState).Methods(http.MethodGet)
}

// GetScrapperState récuperation d'un état de scrapper
func getScrapperState(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

vars := mux.Vars(r)
log.Printf("storeId: %v\n", vars["storeid"])

json.NewEncoder(w).Encode(auchan.GetDriveState(vars["storeid"]))
}

// AddScrapper ajoute un scrapper
func addScrapper(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)

vars := mux.Vars(r)
log.Printf("storeId: %v\n", vars["storeid"])

go auchan.NewDriveHandler(vars["storeid"])
}
32 changes: 32 additions & 0 deletions internal/api/stores.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package api

import (
"encoding/json"
"net/http"

"github.com/gorilla/mux"
"github.com/nlevee/go-auchan-drive-checker/pkg/auchan"
)

// AddStoreRoutes populate router
func addStoreRoutes(r *mux.Router) {
// récuperation des stores
r.HandleFunc("/stores", getStores).Methods(http.MethodGet)
}

// GetStores récupere la liste des stores filtrés
func getStores(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
cp := params["postalCode"]
if len(cp) == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

storeIDs, _ := auchan.GetStoreByPostalCode(string(cp[0]))

json.NewEncoder(w).Encode(storeIDs)
}
55 changes: 20 additions & 35 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,54 +3,39 @@ package main
import (
"flag"
"log"
"net/http"
"os"
"time"

"github.com/gorilla/mux"
"github.com/nlevee/go-auchan-drive-checker/internal/api"
"github.com/nlevee/go-auchan-drive-checker/pkg/auchan"
"github.com/nlevee/go-auchan-drive-checker/pkg/drivestate"
)

func handle(currentState *drivestate.DriveState) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if _, err := w.Write([]byte(`{"message": "` + (*currentState).Dispo + `"}`)); err != nil {
log.Fatal(err)
}
log.Printf("current state is : %v", (*currentState).IsActive)
}
}

var tick = time.NewTicker(2 * time.Minute)
var done = make(chan bool)
var currentState = make(map[string]*drivestate.DriveState)

func addDriveHandler(driveId string) {
config := auchan.NewConfig(driveId)
currentState[driveId] = config.State
go auchan.GetDriveState(config, tick, done)
}

func main() {
auchanDriveId := flag.String("id", "", "The drive Id")
auchanDriveID := flag.String("id", "", "The drive Id")
postalCode := flag.String("cp", "", "The Postal Code")
listenHost := flag.String("host", "0.0.0.0", "Start a server and listen on this host")
listenPort := flag.String("port", "", "Start a server and listen on this port")
flag.Parse()

if *auchanDriveId == "" {
flag.PrintDefaults()
os.Exit(1)
// recherche du driveId si code postal
if *auchanDriveID == "" && *postalCode != "" {
storeIDs, _ := auchan.GetStoreIDByPostalCode(*postalCode)
if len(storeIDs) > 0 {
auchanDriveID = &storeIDs[0]
} else {
log.Fatal("no stores found")
}
}

if *listenPort != "" && *listenHost != "" {
addDriveHandler(*auchanDriveId)
r := mux.NewRouter()
r.HandleFunc("/", handle(currentState[*auchanDriveId])).Methods(http.MethodGet)
log.Fatal(http.ListenAndServe(*listenHost+":"+*listenPort, r))
if *auchanDriveID != "" {
go auchan.NewDriveHandler(*auchanDriveID)
}
api.StartServer(*listenHost, *listenPort)
} else {
config := auchan.NewConfig(*auchanDriveId)
auchan.GetDriveState(config, tick, done)
if *auchanDriveID == "" {
flag.PrintDefaults()
os.Exit(1)
}
auchan.NewDriveHandler(*auchanDriveID)
}
}
Loading

0 comments on commit ebb79a0

Please sign in to comment.