Created
September 23, 2020 03:40
-
-
Save jie-luo/11e05b1398d03b8dd6e133622ec60757 to your computer and use it in GitHub Desktop.
HTTP server - 09/22/2020
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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