Skip to content

Instantly share code, notes, and snippets.

@ismiyati
Created June 4, 2020 09:31
Show Gist options
  • Select an option

  • Save ismiyati/b00911e80b96472706c3969bfd8c47a5 to your computer and use it in GitHub Desktop.

Select an option

Save ismiyati/b00911e80b96472706c3969bfd8c47a5 to your computer and use it in GitHub Desktop.
#GOLANG . replace http server request body
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
)
type Middleware func(http.HandlerFunc) http.HandlerFunc
func MiddlewareStack(mws ...Middleware) (handlerFunc http.HandlerFunc) {
for i := len(mws); i > 0; i-- {
handlerFunc = mws[i-1](handlerFunc)
}
return
}
type Body struct {
data []byte
}
func (b *Body) Read(bs []byte) (n int, err error) {
if len(b.data) != 0 {
n = copy(bs, b.data)
b.data = b.data[n:]
return
}
err = io.EOF
return
}
func (b *Body) Close() error {
return nil
}
var data = "qwertyuiopasdfghjklzxcvbnm"
func MiddleWare1(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = &Body{[]byte(data)} //set data
fmt.Println("MW1->\n")
next.ServeHTTP(w, r)
fmt.Println("MW1<-\n")
})
}
func MiddleWare2(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("MW2->\n")
next.ServeHTTP(w, r)
fmt.Println("MW2<-\n")
})
}
func MiddleWare3(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("MW3->\n")
bs, _ := ioutil.ReadAll(r.Body) //get data
fmt.Println("result:", string(bs), " , expected:", data, "\n")
//next.ServeHTTP(w, r) //last middleware, next == nil
fmt.Println("MW3<-\n")
})
}
func main() {
http.ListenAndServe(":8080", MiddlewareStack(MiddleWare1, MiddleWare2, MiddleWare3)) //akses: http://localhost:8080
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment