Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTTP server - 09/22/2020
package main
import (
"fmt"
_"github.com/joho/godotenv"
"net/http"
"github.com/gorilla/mux"
"encoding/json"
"strconv"
)
type Car struct {
NumberOfWheels int `json:"NumberOfWheels"`
Color string `json:"Color"`
}
var cars []Car = []Car{}
func main() {
//get command line arguments
// args := os.Args
// fmt.Println(args)
// //environment variables
// err := godotenv.Load()
// if err != nil {
// fmt.Println(err)
// }
// secretToken := os.Getenv("SECRET_TOKEN")
// fmt.Println(secretToken)
//server programming
router := mux.NewRouter()
router.HandleFunc("/getCars", getCars).Methods(http.MethodGet)
router.HandleFunc("/createCar", createCar).Methods(http.MethodPost)
http.ListenAndServe(":8080", router)
}
func getCars(response http.ResponseWriter, request *http.Request) {
fmt.Println(cars)
}
func createCar(response http.ResponseWriter, request *http.Request) {
//create a car
newCar := Car{}
//take the car in the request and move the contents to our car
err := json.NewDecoder(request.Body).Decode(&newCar)
if err != nil {
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
cars = append(cars, newCar)
fmt.Fprintf(response, strconv.Itoa(newCar.NumberOfWheels))
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.