github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume4/section3/gopherface/endpoints/findgophers.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/common/authenticate"
    10  
    11  	"github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/common"
    12  )
    13  
    14  func FindGophersEndpoint(env *common.Env) http.HandlerFunc {
    15  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    16  
    17  		gfSession, err := authenticate.SessionStore.Get(r, "gopherface-session")
    18  		if err != nil {
    19  			log.Print(err)
    20  			return
    21  		}
    22  		uuid := gfSession.Values["uuid"].(string)
    23  
    24  		var searchTerm string
    25  		reqBody, err := ioutil.ReadAll(r.Body)
    26  		if err != nil {
    27  			log.Print("Encountered error when attempting to read the request body: ", err)
    28  		}
    29  		err = json.Unmarshal(reqBody, &searchTerm)
    30  		if err != nil {
    31  			log.Print("Encountered error when attempting to unmarshal JSON: ", err)
    32  		}
    33  
    34  		gophers, err := env.DB.FindGophers(uuid, searchTerm)
    35  
    36  		if err != nil {
    37  			log.Print(err)
    38  		}
    39  
    40  		w.Header().Set("Content-Type", "application/json")
    41  		json.NewEncoder(w).Encode(gophers)
    42  
    43  	})
    44  }