Advertisement
darkmist

1_singlehost.go

Jul 20th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.79 KB | None | 0 0
  1. // Go middleware samples for my blog post. http://justinas.org/writing-http-middleware-in-go/
  2.  
  3. package main
  4.  
  5. import (
  6.     "net/http"
  7. )
  8.  
  9. type SingleHost struct {
  10.     handler     http.Handler
  11.     allowedHost string
  12. }
  13.  
  14. func NewSingleHost(handler http.Handler, allowedHost string) *SingleHost {
  15.     return &SingleHost{handler: handler, allowedHost: allowedHost}
  16. }
  17.  
  18. func (s *SingleHost) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  19.     host := r.Host
  20.     if host == s.allowedHost {
  21.         s.handler.ServeHTTP(w, r)
  22.     } else {
  23.         w.WriteHeader(403)
  24.     }
  25. }
  26.  
  27. func myHandler(w http.ResponseWriter, r *http.Request) {
  28.     w.Write([]byte("Success!"))
  29. }
  30.  
  31. func main() {
  32.     single := NewSingleHost(http.HandlerFunc(myHandler), "example.com")
  33.  
  34.     println("Listening on port 8080")
  35.     http.ListenAndServe(":8080", single)
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement