Skip to content

Instantly share code, notes, and snippets.

@aletessier
Forked from alexedwards/main.go
Created March 11, 2016 20:33
Show Gist options
  • Select an option

  • Save aletessier/0ffb97aaea1f201c3203 to your computer and use it in GitHub Desktop.

Select an option

Save aletessier/0ffb97aaea1f201c3203 to your computer and use it in GitHub Desktop.

Revisions

  1. @alexedwards alexedwards renamed this gist Oct 17, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @alexedwards alexedwards renamed this gist Oct 17, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. @alexedwards alexedwards created this gist Oct 17, 2014.
    47 changes: 47 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    package main

    import (
    "bytes"
    "github.com/goji/httpauth"
    "github.com/gorilla/handlers"
    "net/http"
    "os"
    )

    func enforceXMLHandler(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    if r.ContentLength == 0 {
    http.Error(w, http.StatusText(400), 400)
    return
    }

    buf := new(bytes.Buffer)
    buf.ReadFrom(r.Body)
    if http.DetectContentType(buf.Bytes()) != "text/xml; charset=utf-8" {
    http.Error(w, http.StatusText(415), 415)
    return
    }

    next.ServeHTTP(w, r)
    })
    }

    func myLoggingHandler(h http.Handler) http.Handler {
    logFile, err := os.OpenFile("server.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
    panic(err)
    }
    return handlers.LoggingHandler(logFile, h)
    }

    func main() {
    indexHandler := http.HandlerFunc(index)
    authHandler := httpauth.SimpleBasicAuth("username", "password")

    http.Handle("/", myLoggingHandler(authHandler(enforceXMLHandler(indexHandler))))
    http.ListenAndServe(":3000", nil)
    }

    func index(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("OK"))
    }