Skip to content

Commit

Permalink
config of env variables to work in prod and dev
Browse files Browse the repository at this point in the history
  • Loading branch information
karlsb committed Nov 21, 2024
1 parent 1d68570 commit ccde52b
Show file tree
Hide file tree
Showing 10 changed files with 66 additions and 16 deletions.
3 changes: 3 additions & 0 deletions WouldYouRatherBackend/app.yaml
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
runtime: go123
env_variables:
ALLOWED_ORIGIN:"https://whatwouldyourather.netlify.app"
LOG_LEVEL:PROD
Binary file modified WouldYouRatherBackend/build-database/wouldyourather.db
Binary file not shown.
5 changes: 4 additions & 1 deletion WouldYouRatherBackend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ module gcloud-setup-test

go 1.23.3

require modernc.org/sqlite v1.34.1
require (
github.com/joho/godotenv v1.5.1
modernc.org/sqlite v1.34.1
)

require (
github.com/dustin/go-humanize v1.0.1 // indirect
Expand Down
2 changes: 2 additions & 0 deletions WouldYouRatherBackend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ 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/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
Expand Down
22 changes: 19 additions & 3 deletions WouldYouRatherBackend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"os"

"github.com/joho/godotenv"
_ "modernc.org/sqlite" // fast but be careful, since it is written in CGO - might have compatibility issues
)

Expand Down Expand Up @@ -128,8 +129,8 @@ func routeCheckMiddleware(expectedPath string, handler http.HandlerFunc) http.Ha

func enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Origin", "https://whatwouldyourather.netlify.app") //TODO CHANGE HERE IF PRODUCTION
allowed_origin := os.Getenv("ALLOWED_ORIGIN")
w.Header().Set("Access-Control-Allow-Origin", allowed_origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

Expand All @@ -142,6 +143,17 @@ func enableCORS(next http.Handler) http.Handler {

}

func loggerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log_level := os.Getenv("LOG_LEVEL")
if log_level == "DEV" {
log.Println(r.Body)
}
next.ServeHTTP(w, r)
})

}

func storeAnswer(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
Expand Down Expand Up @@ -177,6 +189,10 @@ func storeAnswer(w http.ResponseWriter, r *http.Request) {
}

func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
db.init()
defer db.Close()

Expand All @@ -193,7 +209,7 @@ func main() {
}

log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, enableCORS(mux)); err != nil {
if err := http.ListenAndServe(":"+port, loggerMiddleware(enableCORS(mux))); err != nil {
log.Fatal(err)
}
}
3 changes: 3 additions & 0 deletions WouldYouRatherClient/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

VITE_RANDOM_PAIR_URL=http://localhost:8080/random-pair
VITE_STORE_ANSWER_URL=http://localhost:8080/store-answer
3 changes: 3 additions & 0 deletions WouldYouRatherClient/.env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

VITE_RANDOM_PAIR_URL=https://setuptest-442308.lm.r.appspot.com/random-pair
VITE_STORE_ANSWER_URL=https://setuptest-442308.lm.r.appspot.com/store-answer
13 changes: 13 additions & 0 deletions WouldYouRatherClient/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions WouldYouRatherClient/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"dotenv": "^16.4.5",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
Expand Down
30 changes: 18 additions & 12 deletions WouldYouRatherClient/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
import { useState } from "react"


const url = "https://setuptest-442308.lm.r.appspot.com/random-pair"
const urlPost = "https://setuptest-442308.lm.r.appspot.com/store-answer"
//const devurl = "http://localhost:8080/random-pair"
//const devurlPost = "http://localhost:8080/store-answer"

type Pair = {
id: number
left: string
right: string
}

enum LEFTRIGHT {
LEFT = "left",
RIGHT = "right"
}

type CardProps = {
children: React.ReactNode
leftright: LEFTRIGHT
id: number
}

const random_pair_url = import.meta.env.VITE_RANDOM_PAIR_URL
const store_answer_url = import.meta.env.VITE_STORE_ANSWER_URL

//TODO consider sending a full pair as props, to make it cleaner
function Card(props: CardProps){
const handleClick = async (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.preventDefault()
const res = await fetch(urlPost, {method:"POST", headers: {"Content-Type":"application/json"}}) //need to attach payload
const res = await fetch(store_answer_url, {method:"POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({"id":props.id , "leftright": props.leftright })}) //need to attach payload
if(res.ok) {
const data = await res.json()
console.log(data)
Expand All @@ -40,13 +46,13 @@ function Card(props: CardProps){


function App() {
const [pair,setPair] = useState<Pair>({left:"Welcome to",right:"Would you rather"})
const [pair,setPair] = useState<Pair>({id:-1, left:"Welcome to",right:"Would you rather"})

async function apiCall(){
const res = await fetch(url, {method:"GET", headers: {"Content-Type":"application/json"}})
const res = await fetch(random_pair_url, {method:"GET", headers: {"Content-Type":"application/json"}})
if(res.ok) {
const data = await res.json()
setPair({left:data.pair.left, right:data.pair.right})
setPair({id:data.pair.id, left:data.pair.left, right:data.pair.right})
}
else{
console.log("API call failed", res.status)
Expand All @@ -63,8 +69,8 @@ function App() {
<div className="h-5/6 bg-blue-100 flex flex-col justify-center items-center">{/* Main content*/}
<div className="w-full h-5/6 flex justify-center items-center">
<div className="w-3/5 h-4/5 flex">
<Card>{pair.left}</Card>
<Card>{pair.right}</Card>
<Card leftright={LEFTRIGHT.LEFT} id={pair.id}>{pair.left}</Card>
<Card leftright={LEFTRIGHT.RIGHT} id={pair.id}>{pair.right}</Card>
</div>
</div>
<div className="" >
Expand Down

0 comments on commit ccde52b

Please sign in to comment.