github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/core/corehttp/ipns_hostname.go (about)

     1  package corehttp
     2  
     3  import (
     4  	"net"
     5  	"net/http"
     6  	"strings"
     7  
     8  	isd "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-is-domain"
     9  	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
    10  	"github.com/ipfs/go-ipfs/core"
    11  )
    12  
    13  // IPNSHostnameOption rewrites an incoming request if its Host: header contains
    14  // an IPNS name.
    15  // The rewritten request points at the resolved name on the gateway handler.
    16  func IPNSHostnameOption() ServeOption {
    17  	return func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
    18  		childMux := http.NewServeMux()
    19  		mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    20  			ctx, cancel := context.WithCancel(n.Context())
    21  			defer cancel()
    22  
    23  			host := strings.SplitN(r.Host, ":", 2)[0]
    24  			if len(host) > 0 && isd.IsDomain(host) {
    25  				name := "/ipns/" + host
    26  				if _, err := n.Namesys.Resolve(ctx, name); err == nil {
    27  					r.Header["X-IPNS-Original-Path"] = []string{r.URL.Path}
    28  					r.URL.Path = name + r.URL.Path
    29  				}
    30  			}
    31  			childMux.ServeHTTP(w, r)
    32  		})
    33  		return childMux, nil
    34  	}
    35  }