github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume3/section1/basics/basics.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"html/template"
     7  	"io/ioutil"
     8  	"log"
     9  	"net/http"
    10  	"strings"
    11  
    12  	"github.com/gorilla/mux"
    13  )
    14  
    15  func renderTemplate(w http.ResponseWriter, templateFile string, templateData interface{}) {
    16  	t, err := template.ParseFiles(templateFile)
    17  	if err != nil {
    18  		log.Fatal("Error encountered while parsing the template: ", err)
    19  	}
    20  	t.Execute(w, templateData)
    21  }
    22  
    23  func BasicsHandler() http.Handler {
    24  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    25  		renderTemplate(w, "./templates/basics.html", nil)
    26  	})
    27  }
    28  
    29  func LowercaseTextTransformHandler() http.Handler {
    30  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    31  		var s string
    32  
    33  		reqBody, err := ioutil.ReadAll(r.Body)
    34  		if err != nil {
    35  			log.Print("Encountered error when attempting to read the request body: ", err)
    36  		}
    37  
    38  		reqBodyString := string(reqBody)
    39  
    40  		err = json.Unmarshal([]byte(reqBodyString), &s)
    41  		if err != nil {
    42  			log.Print("Encountered error when attempting to unmarshal JSON: ", err)
    43  		}
    44  
    45  		textBytes, err := json.Marshal(strings.ToLower(s))
    46  		if err != nil {
    47  			log.Print("Encountered error when attempting ot marshal JSON: ", err)
    48  		}
    49  		fmt.Println("textBytes string: ", string(textBytes))
    50  		w.Write(textBytes)
    51  
    52  	})
    53  
    54  }
    55  
    56  func main() {
    57  
    58  	r := mux.NewRouter()
    59  
    60  	r.Handle("/", BasicsHandler()).Methods("GET")
    61  	r.Handle("/lowercase-text", LowercaseTextTransformHandler())
    62  
    63  	fs := http.FileServer(http.Dir("./static"))
    64  	http.Handle("/", r)
    65  	http.Handle("/static/", http.StripPrefix("/static", fs))
    66  	http.ListenAndServe(":8080", nil)
    67  
    68  }