func user()

in http/simple/server/app/server.go [39:87]


func user(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case constant.Post:
		byts, err := ioutil.ReadAll(r.Body)
		if err != nil {
			w.Write([]byte(err.Error()))
		}
		var user User
		err = json.Unmarshal(byts, &user)
		if err != nil {
			w.Write([]byte(err.Error()))
		}
		_, ok := cache.Get(user.Name)
		if ok {
			w.Header().Set(constant.HeaderKeyContextType, constant.HeaderValueJsonUtf8)
			w.Write([]byte("{\"message\":\"data is exist\"}"))
			return
		}
		user.ID = randSeq(5)
		if cache.Add(&user) {
			b, _ := json.Marshal(&user)
			w.Header().Set(constant.HeaderKeyContextType, constant.HeaderValueJsonUtf8)
			w.Write(b)
			return
		}
		w.Write(nil)
	case constant.Get:
		subPath := strings.TrimPrefix(r.URL.Path, "/user/")
		userName := strings.Split(subPath, "/")[0]
		var u *User
		var b bool
		if len(userName) != 0 {
			log.Printf("paths: %v", userName)
			u, b = cache.Get(userName)
		} else {
			q := r.URL.Query()
			u, b = cache.Get(q.Get("name"))
		}
		// w.WriteHeader(200)
		if b {
			b, _ := json.Marshal(u)
			w.Header().Set(constant.HeaderKeyContextType, constant.HeaderValueJsonUtf8)
			w.Write(b)
			return
		}
		w.WriteHeader(http.StatusNotFound)
		w.Write(nil)
	}
}