darkmist

Build Your Own Web Framework in Go.go

Jul 20th, 2017
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.09 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "github.com/goji/httpauth"
  6.     "github.com/gorilla/handlers"
  7.     "net/http"
  8.     "os"
  9. )
  10.  
  11. func enforceXMLHandler(next http.Handler) http.Handler {
  12.     return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  13.         if r.ContentLength == 0 {
  14.             http.Error(w, http.StatusText(400), 400)
  15.             return
  16.         }
  17.  
  18.         buf := new(bytes.Buffer)
  19.         buf.ReadFrom(r.Body)
  20.         if http.DetectContentType(buf.Bytes()) != "text/xml; charset=utf-8" {
  21.             http.Error(w, http.StatusText(415), 415)
  22.             return
  23.         }
  24.  
  25.         next.ServeHTTP(w, r)
  26.     })
  27. }
  28.  
  29. func myLoggingHandler(h http.Handler) http.Handler {
  30.     logFile, err := os.OpenFile("server.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  31.     if err != nil {
  32.         panic(err)
  33.     }
  34.     return handlers.LoggingHandler(logFile, h)
  35. }
  36.  
  37. func main() {
  38.     indexHandler := http.HandlerFunc(index)
  39.     authHandler := httpauth.SimpleBasicAuth("username", "password")
  40.  
  41.     http.Handle("/", myLoggingHandler(authHandler(enforceXMLHandler(indexHandler))))
  42.     http.ListenAndServe(":3000", nil)
  43. }
  44.  
  45. func index(w http.ResponseWriter, r *http.Request) {
  46.     w.Write([]byte("OK"))
  47. }
Advertisement
Add Comment
Please, Sign In to add comment