github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume4/section3/gopherface/endpoints/savepost.go (about)

     1  package endpoints
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"log"
     7  	"net/http"
     8  
     9  	"github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/models/socialmedia"
    10  
    11  	"github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/common/authenticate"
    12  
    13  	"github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/common"
    14  )
    15  
    16  func SavePostEndpoint(env *common.Env) http.HandlerFunc {
    17  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    18  
    19  		gfSession, err := authenticate.SessionStore.Get(r, "gopherface-session")
    20  		if err != nil {
    21  			log.Print(err)
    22  			return
    23  		}
    24  		uuid := gfSession.Values["uuid"].(string)
    25  
    26  		reqBody, err := ioutil.ReadAll(r.Body)
    27  		if err != nil {
    28  			log.Print("Encountered error when attempting to read the request body: ", err)
    29  		}
    30  
    31  		var p socialmedia.Post
    32  		json.Unmarshal(reqBody, &p)
    33  
    34  		err = env.DB.SavePost(uuid, p.Caption, p.MessageBody, p.RawMoodValue)
    35  
    36  		if err != nil {
    37  			w.Write([]byte("ERROR: Failed to save post!"))
    38  		} else {
    39  			w.Write([]byte("Post saved successfully!"))
    40  		}
    41  
    42  	})
    43  }