Skip to content

Instantly share code, notes, and snippets.

@karronoli
Last active March 30, 2016 09:45
Show Gist options
  • Save karronoli/4260bb9a6302e207341905941c32ed47 to your computer and use it in GitHub Desktop.
Save karronoli/4260bb9a6302e207341905941c32ed47 to your computer and use it in GitHub Desktop.
Go web server can be restricted access by ALLOW_HOST. (go build allow-hostaddr-httpd.go && env ALLOW_HOST=example.com ./allow-hostaddr-httpd )
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
)
func main() {
http.HandleFunc("/", handler)
panic(http.ListenAndServe(":" + os.Getenv("PORT"), nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
ip := r.Header.Get("X-Forwarded-For")
ips, err := net.LookupHost(os.Getenv("ALLOW_HOST"))
if err != nil {
panic(err)
}
ok_ip := ""
for _, _ip := range ips {
fmt.Fprintf(w, "%s %s", _ip, ip)
if ip == _ip {
ok_ip = _ip
}
}
if ok_ip == "" {
panic(err)
}
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
path := filepath.Join(cwd, filepath.Clean(r.RequestURI))
contents, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
w.Write(contents)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment