Last active
September 11, 2018 06:16
-
-
Save yukpiz/8c095d84f837994e9fccf45f1dbcc213 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"encoding/json" | |
"fmt" | |
"github.com/julienschmidt/httprouter" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
type Profile struct { | |
Name string `json:"name"` | |
Age int `json:"age"` | |
Gender string `json:"gender"` | |
FavoriteFoods []string `json:"favorite_foods"` | |
} | |
var savedProfiles map[string]Profile = map[string]Profile{} | |
func PostProfile(w http.ResponseWriter, r *http.Request, p httprouter.Params) { | |
defer r.Body.Close() | |
body, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
var reqProfile Profile | |
err = json.Unmarshal(body, &reqProfile) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
if reqProfile.Name == "" { | |
http.Error(w, "name is required.", http.StatusBadRequest) | |
return | |
} | |
savedProfiles[reqProfile.Name] = reqProfile | |
fmt.Fprintf(w, fmt.Sprintf("%d Created", http.StatusCreated)) | |
} | |
func main() { | |
router := httprouter.New() | |
router.POST("/Profile", PostProfile) | |
err := http.ListenAndServe(":8080", router) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment