Skip to content

Instantly share code, notes, and snippets.

@jie-luo
Created September 23, 2020 03:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jie-luo/11e05b1398d03b8dd6e133622ec60757 to your computer and use it in GitHub Desktop.
Save jie-luo/11e05b1398d03b8dd6e133622ec60757 to your computer and use it in GitHub Desktop.
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