42
loading...
This website collects cookies to deliver better user experience
func postHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
// create a variable of our defined struct type Lesson
var tempLesson Lesson
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&tempLesson)
if err != nil {
panic(err)
}
defer r.Body.Close()
fmt.Printf("Title: %s. Summary: %s\n", tempLesson.Title, tempLesson.Summary)
w.WriteHeader(http.StatusCreated)
w.Write([]byte("201 - Created"))
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("405 - Method Not Allowed"))
}
}
r.Method == "POST"
for better clarity.Lesson
, you will see this depicted in the snippet that shows the package, imports and the main
function below.
func filterContentType(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Inside filterContentType middleware, before the request is handled")
// filter requests by mime type
if r.Header.Get("Content-Type") != "application/json" {
w.WriteHeader(http.StatusUnsupportedMediaType)
w.Write([]byte("415 - Unsupported Media Type. JSON type is expected"))
return
}
// handle the request
handler.ServeHTTP(w, r)
log.Println("Inside filterContentType middleware, after the request was handled")
})
}
unc setServerTimeCookie(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Inside setServerTimeCookie middleware, before the request is handled")
// handles the request
handler.ServeHTTP(w, r)
cookie := http.Cookie{Name: "Server Time(UTC)", Value: strconv.FormatInt(time.Now().Unix(), 10)}
http.SetCookie(w, &cookie)
log.Println("Inside setServerTimeCookie middleware, after the request is handled")
})
}
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
)
type Lesson struct {
Title string
Summary string
}
func main() {
port := ":8080"
originalHandler := http.HandlerFunc(postHandler)
http.Handle("/lesson", filterContentType(setServerTimeCookie(originalHandler)))
//http.HandleFunc("/city", poastHandler)
log.Fatal(http.ListenAndServe(port, nil))
}
filterContentType(setServerTimeCookie(originalHandler))
http.Handle("/lesson", filterContentType(setServerTimeCookie(http.HandlerFunc(postHandler))))
curl http://localhost:8080/city -d '{"title": "middleware with Go", "summary": "learn some middleware concepts with a quick and dirty demo"}'
415 - Unsupported Media Type. JSON type expected%
response to your test. curl -i -H "Content-Type: application/json" -X POST http://localhost:8080/city -d '{"title": "Middleware demo with Go", "summary": "Hopefully a successful demo now that we have specified mime type and the method"}'
Hopefully your output is similar to below.
`HTTP/1.1 200 OK
Date: Tue, 27 Jul 2021 20:09:52 GMT
Content-Length: 13
Content-Type: text/plain; charset=utf-8
201 - Created%`