Last active
September 11, 2018 06:17
-
-
Save yukpiz/82cbcf95b2b3fbd7c4fec0962d45667b to your computer and use it in GitHub Desktop.
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 ( | |
"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 GetProfile(w http.ResponseWriter, r *http.Request, p httprouter.Params) { | |
name := p.ByName("name") | |
resProfile, found := savedProfiles[name] | |
if !found { | |
http.Error(w, fmt.Sprintf("%d Not Found", http.StatusNotFound), http.StatusNotFound) | |
return | |
} | |
bytes, err := json.Marshal(resProfile) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
} | |
fmt.Fprintf(w, string(bytes)) | |
} | |
func main() { | |
router := httprouter.New() | |
router.POST("/Profile", PostProfile) | |
router.GET("/Profile/:name", GetProfile) | |
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