Exemple #1
0
func wouldMatch(router *mux.Router, rq *http.Request, method string) bool {
	savedMethod := rq.Method
	rq.Method = method
	defer func() { rq.Method = savedMethod }()
	var matchInfo mux.RouteMatch
	return router.Match(rq, &matchInfo)
}
Exemple #2
0
func (this *GoChromeCastHttpServer) DownloadPlay(c web.C, w http.ResponseWriter, r *http.Request) {
	if params, err := utils.GetParams(r, "id", "file_path"); err != nil {
		w.Header().Set("Content-Type", "application/json")
		r := responses.JsonResponse{}
		r.Method = "DownloadPlay"
		r.Set(nil, err)
		io.WriteString(w, utils.RenderResponse(r))
	} else {
		if sc, display_path, err := this.ds.DownloadPlay(params["id"], params["file_path"]); err != nil {
			w.Header().Set("Content-Type", "application/json")
			r := responses.JsonResponse{}
			r.Method = "DownloadPlay"
			r.Set(nil, err)
			io.WriteString(w, utils.RenderResponse(r))
		} else {
			defer func() {
				if err == nil {
					sc.Close()
				}
			}()
			w.Header().Set("Content-Disposition", "attachment; filename=\""+params["file_path"]+"\"")
			http.ServeContent(w, r, display_path, time.Now(), sc)
		}
	}
}
Exemple #3
0
func main() {
	f, err := os.OpenFile("./file.exe", os.O_RDWR, 0666) //其实这里的 O_RDWR应该是 O_RDWR|O_CREATE,也就是文件不存在的情况下就建一个空文件,但是因为windows下还有BUG,如果使用这个O_CREATE,就会直接清空文件,所以这里就不用了这个标志,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}
	stat, err := f.Stat() //获取文件状态
	if err != nil {
		panic(err)
	}
	f.Seek(stat.Size(), 0) //把文件指针指到文件末,当然你说为何不直接用 O_APPEND 模式打开,没错是可以。我这里只是试验。
	url := "http://dl.google.com/chrome/install/696.57/chrome_installer.exe"
	var req http.Request
	req.Method = "GET"
	//req.UserAgent = UA
	req.Close = true
	req.URL, err = http.ParseURL(url)
	if err != nil {
		panic(err)
	}
	header := http.Header{}
	header.Set("Range", "bytes="+strconv.Itoa64(stat.Size)+"-")
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err != nil {
		panic(err)
	}
	written, err := io.Copy(f, resp.Body)
	if err != nil {
		panic(err)
	}
	println("written: ", written)
}
Exemple #4
0
// Put issues a PUT to the specified URL.
// Caller should close r.Body when done reading it.
func authPut(url_, user, pwd, client, clientURL, version, agent, bodyType string,
	body io.Reader) (r *http.Response, err error) {
	var req http.Request
	req.Method = "PUT"
	req.Body = body.(io.ReadCloser)
	if user != "" && pwd != "" {
		req.Header = map[string][]string{
			"Content-Type":           {bodyType},
			"Transfer-Encoding":      {"chunked"},
			"User-Agent":             {agent},
			"X-Fluidinfo-Client":     {client},
			"X-Fluidinfo-Client-URL": {clientURL},
			"X-Fluidinfo-Version":    {version},
			"Authorization":          {"Basic " + encodedUsernameAndPassword(user, pwd)},
		}
	} else {
		req.Header = map[string][]string{
			"Content-Type":           {bodyType},
			"Transfer-Encoding":      {"chunked"},
			"User-Agent":             {agent},
			"X-Fluidinfo-Client":     {client},
			"X-Fluidinfo-Client-URL": {clientURL},
			"X-Fluidinfo-Version":    {version},
		}
	}

	req.URL, err = url.Parse(url_)
	if err != nil {
		return nil, err
	}

	return send(&req)
}
Exemple #5
0
// ServeHTTP servers the actual HTTP request by buidling a context and running
// it through all the handlers.
func (handler *HttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
	// override the method if needed
	method := request.Header.Get("X-HTTP-Method-Override")
	if method != "" {
		request.Method = method
	}

	// make the context
	ctx := webcontext.NewWebContext(responseWriter, request, handler.codecService)

	// copy the data
	for k, v := range handler.Data {
		ctx.Data()[k] = v
	}

	// run it through the handlers
	_, err := handler.Handlers.Handle(ctx)

	// do we need to handle an error?
	if err != nil {

		// set the error
		ctx.Data().Set(DataKeyForError, err)

		// tell the handler to handle it
		handler.ErrorHandler().Handle(ctx)

	}

}
Exemple #6
0
func Translate(from, to, s string) (t string, err error) {
	var url_ = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&format=text&q=" + url.QueryEscape(s) + "&langpair=" + url.QueryEscape(from) + "%7C" + url.QueryEscape(to)
	var r *http.Response
	if proxy := os.Getenv("HTTP_PROXY"); len(proxy) > 0 {
		proxy_url, _ := url.Parse(proxy)
		tcp, _ := net.Dial("tcp", proxy_url.Host)
		conn := httputil.NewClientConn(tcp, nil)
		var req http.Request
		req.URL, _ = url.Parse(url_)
		req.Method = "GET"
		r, err = conn.Do(&req)
	} else {
		r, err = http.Get(url_)
	}
	if err == nil {
		defer r.Body.Close()
		if b, err := ioutil.ReadAll(r.Body); err == nil {
			var r interface{}
			if err = json.NewDecoder(bytes.NewBuffer(b)).Decode(&r); err == nil {
				if r.(map[string]interface{})["responseStatus"].(float64) == 200 {
					return r.(map[string]interface{})["responseData"].(map[string]interface{})["translatedText"].(string), nil
				} else {
					err = errors.New(r.(map[string]interface{})["responseDetails"].(string))
				}
			}
		}
	}
	return "", err
}
func getCodes() {
	//并发写文件必须要有锁啊,怎么还是串行程序的思维啊。
	fileName := "./data/data.html"

	f, err := os.Create(fileName) //其实这里的 O_RDWR应该是 O_RDWR|O_CREATE,也就是文件不存在的情况下就建一个空文件,但是因为windows下还有BUG,如果使用这个O_CREATE,就会直接清空文件,所以这里就不用了这个标志,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}

	defer f.Close()

	urls := "http://quote.eastmoney.com/stocklist.html"
	var req http.Request
	req.Method = "GET"
	req.Close = true
	req.URL, err = url.Parse(urls)
	if err != nil {
		panic(err)
	}

	header := http.Header{}
	header.Set("User-Agent", UA)
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err == nil {
		if resp.StatusCode == 200 {
			io.Copy(f, resp.Body)
		} else {
			fmt.Println("http get StatusCode")
		}
		defer resp.Body.Close()
	} else {
		fmt.Println("http get error")
	}
}
Exemple #8
0
// Put returns *BeegoHttpRequest with PUT method.
func Put(url string) *BeegoHttpRequest {
	var req http.Request
	var resp http.Response
	req.Method = "PUT"
	req.Header = http.Header{}
	return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil}
}
Exemple #9
0
func post(url_ string, oauthHeaders map[string]string) (r *http.Response, err error) {
	var req http.Request
	req.Method = "POST"
	req.ProtoMajor = 1
	req.ProtoMinor = 1
	req.Close = true
	req.Header = map[string][]string{
		"Authorization": {"OAuth "},
	}
	req.TransferEncoding = []string{"chunked"}

	first := true
	for k, v := range oauthHeaders {
		if first {
			first = false
		} else {
			req.Header["Authorization"][0] += ",\n    "
		}
		req.Header["Authorization"][0] += k + "=\"" + v + "\""
	}

	req.URL, err = url.Parse(url_)
	if err != nil {
		return nil, err
	}

	return send(&req)
}
Exemple #10
0
func TestServeFile(t *testing.T) {
	defer afterTest(t)
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ServeFile(w, r, "testdata/file")
	}))
	defer ts.Close()

	var err error

	file, err := ioutil.ReadFile(testFile)
	if err != nil {
		t.Fatal("reading file:", err)
	}

	// set up the Request (re-used for all tests)
	var req http.Request
	req.Header = make(http.Header)
	if req.URL, err = url.Parse(ts.URL); err != nil {
		t.Fatal("ParseURL:", err)
	}
	req.Method = "GET"

	// straight GET
	_, body := getBody(t, "straight get", req)
	if !bytes.Equal(body, file) {
		t.Fatalf("body mismatch: got %q, want %q", body, file)
	}
}
Exemple #11
0
func download(dictId string, dictNum string, downUrl string) {
	fileName := SAVEPATH + dictId + "-" + dictNum + ".scel"
	f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0666) //其实这里的 O_RDWR应该是 O_RDWR|O_CREATE,也就是文件不存在的情况下就建一个空文件,但是因为windows下还有BUG,如果使用这个O_CREATE,就会直接清空文件,所以这里就不用了这个标志,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}

	defer f.Close()

	var req http.Request
	req.Method = "GET"
	req.Close = true
	req.URL, _ = url.Parse(downUrl)

	header := http.Header{}
	header.Set("User-Agent", UA)
	header.Set("Host", HOST)
	header.Set("Referer", REFERER+dictId)
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err == nil {
		if resp.StatusCode == 200 {
			fmt.Println(dictId + ":sucess")
			_, err = io.Copy(f, resp.Body)
			if err != nil {
				panic(err)
			}
		} else {
			fmt.Println(dictId + ":" + strconv.Itoa(resp.StatusCode))
		}
		defer resp.Body.Close()
	} else {
		fmt.Println(dictId + ":error")
	}
}
Exemple #12
0
func AllowMethods(w http.ResponseWriter, r *http.Request, methods ...string) bool {
	r.Method = strings.ToUpper(r.Method)
	addHead := false
	for _, method := range methods {
		if method == r.Method {
			return true
		}
		if method == GET {
			if r.Method == HEAD {
				return true
			}
			addHead = true
		}
	}
	allow := strings.Join(methods, ", ")
	if addHead {
		allow = "HEAD, " + allow
	}
	w.Header().Set(Allow, allow)
	if r.Method == OPTIONS {
		w.WriteHeader(http.StatusOK)
		return false
	}
	msg := "requires one of: " + allow
	http.Error(w, msg, http.StatusMethodNotAllowed)
	return false
}
Exemple #13
0
func Delete(url string) *HttpRequestBuilder {
	var req http.Request
	req.Method = "DELETE"
	req.Header = http.Header{}
	req.Header.Set("User-Agent", defaultUserAgent)
	return &HttpRequestBuilder{url, &req, nil, map[string]string{}}
}
Exemple #14
0
// Head returns *BeegoHttpRequest with HEAD method.
func Head(url string) *BeegoHttpRequest {
	var req http.Request
	req.Method = "HEAD"
	req.Header = http.Header{}
	req.Header.Set("User-Agent", defaultUserAgent)
	return &BeegoHttpRequest{url, &req, map[string]string{}, false, 60 * time.Second, 60 * time.Second, nil, nil, nil}
}
Exemple #15
0
func (p *WebsocketProxy) Proxy(w http.ResponseWriter, r *http.Request) {
	hj, ok := w.(http.Hijacker)
	if !ok {
		log.Println("hijack assertion failed", r.Host, r.URL.Path)
		p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
		return
	}
	conn, rw, err := hj.Hijack()
	if err != nil {
		log.Println("hijack failed", r.Host, r.URL.Path, err)
		p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
		return
	}
	defer conn.Close()
	rw.Flush()

	wrapreq := new(http.Request)
	wrapreq.Proto = "HTTP/1.1"
	wrapreq.ProtoMajor, wrapreq.ProtoMinor = 1, 1
	wrapreq.Method = "WEBSOCKET"
	wrapreq.Host = r.Host
	const dummy = "/"
	wrapreq.URL = &url.URL{Path: dummy}
	var buf bytes.Buffer
	r.Write(&buf)
	wrapreq.Body = ioutil.NopCloser(io.MultiReader(&buf, conn))
	resp, err := p.transport.RoundTrip(wrapreq)
	if err != nil || resp.StatusCode != 200 {
		io.WriteString(conn, "HTTP/1.0 503 Gateway Failed\r\n")
		io.WriteString(conn, "Connection: close\r\n\r\n")
		return
	}
	defer resp.Body.Close()
	io.Copy(conn, resp.Body)
}
Exemple #16
0
// ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path.
func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	if !strings.HasPrefix(path, "/") {
		OtherErrorHandler(w, r, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	components := strings.Split(path[1:], "/")
	l := len(components)
	var verb string
	if idx := strings.LastIndex(components[l-1], ":"); idx == 0 {
		OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	} else if idx > 0 {
		c := components[l-1]
		components[l-1], verb = c[:idx], c[idx+1:]
	}

	if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && isPathLengthFallback(r) {
		r.Method = strings.ToUpper(override)
		if err := r.ParseForm(); err != nil {
			OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest)
			return
		}
	}
	for _, h := range s.handlers[r.Method] {
		pathParams, err := h.pat.Match(components, verb)
		if err != nil {
			continue
		}
		h.h(w, r, pathParams)
		return
	}

	// lookup other methods to handle fallback from GET to POST and
	// to determine if it is MethodNotAllowed or NotFound.
	for m, handlers := range s.handlers {
		if m == r.Method {
			continue
		}
		for _, h := range handlers {
			pathParams, err := h.pat.Match(components, verb)
			if err != nil {
				continue
			}
			// X-HTTP-Method-Override is optional. Always allow fallback to POST.
			if isPathLengthFallback(r) {
				if err := r.ParseForm(); err != nil {
					OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest)
					return
				}
				h.h(w, r, pathParams)
				return
			}
			OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
			return
		}
	}
	OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
Exemple #17
0
func (e Post) Target(r *http.Request) {
	r.Body = ioutil.NopCloser(bytes.NewBuffer(e.Body))
	r.ContentLength = int64(len(e.Body))
	r.Header.Set("Content-Type", e.ContentType)
	r.Method = "POST"
	r.URL = e.URL
}
Exemple #18
0
// This method handles all requests.  It dispatches to handleInternal after
// handling / adapting websocket connections.
func handle(w http.ResponseWriter, r *http.Request) {
	if maxRequestSize := int64(Config.IntDefault("http.maxrequestsize", 0)); maxRequestSize > 0 {
		r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
	}

	upgrade := r.Header.Get("Upgrade")
	if upgrade == "websocket" || upgrade == "Websocket" {
		websocket.Handler(func(ws *websocket.Conn) {
			//Override default Read/Write timeout with sane value for a web socket request
			ws.SetDeadline(time.Now().Add(time.Hour * 24))
			r.Method = "WS"
			handleInternal(w, r, ws)
		}).ServeHTTP(w, r)
	} else {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers",
			"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-session, X-adm-token")

		// Stop here for a Preflighted OPTIONS request.
		if r.Method == "OPTIONS" {
			return
		}

		handleInternal(w, r, nil)
	}
}
Exemple #19
0
func authzViaPOST(r *http.Request, tok string) int {
	r.Method = "POST"
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	r.Body = ioutil.NopCloser(strings.NewReader(
		url.Values{"api_token": {tok}}.Encode()))
	return http.StatusUnauthorized
}
Exemple #20
0
// ApplyTo sets the requests Method to PUT, URL and Body
func (p Put) ApplyTo(req *http.Request) {
	req.Method = "PUT"
	req.URL = p.URL
	req.Body = ioutil.NopCloser(bytes.NewBuffer(p.Body))
	req.ContentLength = int64(len(p.Body))
	req.Header.Set("Content-Type", p.ContentType)
}
Exemple #21
0
// NewFastHTTPHandler wraps net/http handler to fasthttp request handler,
// so it can be passed to fasthttp server.
//
// While this function may be used for easy switching from net/http to fasthttp,
// it has the following drawbacks comparing to using manually written fasthttp
// request handler:
//
//     * A lot of useful functionality provided by fasthttp is missing
//       from net/http handler.
//     * net/http -> fasthttp handler conversion has some overhead,
//       so the returned handler will be always slower than manually written
//       fasthttp handler.
//
// So it is advisable using this function only for quick net/http -> fasthttp
// switching. Then manually convert net/http handlers to fasthttp handlers
// according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
func NewFastHTTPHandler(h http.Handler) fasthttp.RequestHandler {
	return func(ctx *fasthttp.RequestCtx) {
		var r http.Request

		body := ctx.PostBody()
		r.Method = string(ctx.Method())
		r.Proto = "HTTP/1.1"
		r.ProtoMajor = 1
		r.ProtoMinor = 1
		r.RequestURI = string(ctx.RequestURI())
		r.ContentLength = int64(len(body))
		r.Host = string(ctx.Host())
		r.RemoteAddr = ctx.RemoteAddr().String()

		hdr := make(http.Header)
		ctx.Request.Header.VisitAll(func(k, v []byte) {
			hdr.Set(string(k), string(v))
		})
		r.Header = hdr
		r.Body = &netHTTPBody{body}

		var w netHTTPResponseWriter
		h.ServeHTTP(&w, &r)

		ctx.SetStatusCode(w.StatusCode())
		for k, vv := range w.Header() {
			for _, v := range vv {
				ctx.Response.Header.Set(k, v)
			}
		}
		ctx.Write(w.body)
	}
}
Exemple #22
0
// Implement the http.Handler interface.
func (handler *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Allow overriding the HTTP method. The reason for this is
	// that some libraries/environments to not support PATCH and
	// DELETE requests, e.g. Flash in a browser and parts of Java
	if newMethod := r.Header.Get("X-HTTP-Method-Override"); newMethod != "" {
		r.Method = newMethod
	}

	go handler.logger.Println(r.Method, r.URL.Path)

	header := w.Header()

	if origin := r.Header.Get("Origin"); origin != "" {
		header.Set("Access-Control-Allow-Origin", origin)

		if r.Method == "OPTIONS" {
			// Preflight request
			header.Set("Access-Control-Allow-Methods", "POST, GET, HEAD, PATCH, DELETE, OPTIONS")
			header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata")
			header.Set("Access-Control-Max-Age", "86400")

		} else {
			// Actual request
			header.Set("Access-Control-Expose-Headers", "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata")
		}
	}

	// Set current version used by the server
	header.Set("Tus-Resumable", "1.0.0")

	// Add nosniff to all responses https://golang.org/src/net/http/server.go#L1429
	header.Set("X-Content-Type-Options", "nosniff")

	// Set appropriated headers in case of OPTIONS method allowing protocol
	// discovery and end with an 204 No Content
	if r.Method == "OPTIONS" {
		if handler.config.MaxSize > 0 {
			header.Set("Tus-Max-Size", strconv.FormatInt(handler.config.MaxSize, 10))
		}

		header.Set("Tus-Version", "1.0.0")
		header.Set("Tus-Extension", "creation,concatenation,termination")

		w.WriteHeader(http.StatusNoContent)
		return
	}

	// Test if the version sent by the client is supported
	// GET methods are not checked since a browser may visit this URL and does
	// not include this header. This request is not part of the specification.
	if r.Method != "GET" && r.Header.Get("Tus-Resumable") != "1.0.0" {
		handler.sendError(w, r, ErrUnsupportedVersion)
		return
	}

	// Proceed with routing the request
	handler.routeHandler.ServeHTTP(w, r)
}
Exemple #23
0
func TestValidatesJsonPost(t *testing.T) {
	r := new(http.Request)
	r.Method = "POST"
	r.Header = make(http.Header)
	r.Header.Set("Content-Type", "application/json")
	if WasJsonPost(r) == false {
		t.Error("Expecting JSON post true")
	}
	r.Method = "GET"
	if WasJsonPost(r) {
		t.Error("Expecting JSON post false")
	}
	r.Method = "POST"
	r.Header.Set("Content-Type", "text/html")
	if WasJsonPost(r) {
		t.Error("Expecting JSON post false")
	}
}
Exemple #24
0
func makeRequest(params map[string]string) (*http.Request, error) {
	r := new(http.Request)
	r.Method = params["METHOD"]
	if r.Method == "" {
		return nil, errors.New("mongrel2: no METHOD")
	}

	r.Proto = params["VERSION"]
	var ok bool
	r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto)
	if !ok {
		return nil, errors.New("mongrel2: invalid protocol version")
	}

	r.Trailer = http.Header{}
	r.Header = http.Header{}

	r.Host = params["Host"]
	r.Header.Set("Referer", params["Referer"])
	r.Header.Set("User-Agent", params["User-Agent"])

	if lenstr := params["Content-Length"]; lenstr != "" {
		clen, err := strconv.ParseInt(lenstr, 10, 64)
		if err != nil {
			return nil, errors.New("mongrel2: bad Content-Length")
		}
		r.ContentLength = clen
	}

	for k, v := range params {
		if !skipHeader[k] {
			r.Header.Add(k, v)
		}
	}

	// TODO: cookies

	if r.Host != "" {
		url_, err := url.Parse("http://" + r.Host + params["URI"])
		if err != nil {
			return nil, errors.New("mongrel2: failed to parse host and URI into a URL")
		}
		r.URL = url_
	}
	if r.URL == nil {
		url_, err := url.Parse(params["URI"])
		if err != nil {
			return nil, errors.New("mongrel2: failed to parse URI into a URL")
		}
		r.URL = url_
	}

	// TODO: how do we know if we're using HTTPS?
	// TODO: fill in r.RemoteAddr

	return r, nil
}
Exemple #25
0
func endpointPageHandler(w http.ResponseWriter, r *http.Request, bctx *BasePageContext) {
	vars := mux.Vars(r)
	ctx := &struct {
		*BasePageContext
		Form     endpointForm
		AllUsers []*config.User
		Certs    []string
	}{
		BasePageContext: bctx,
		AllUsers:        bctx.Globals.GetUsers(),
		Certs:           bctx.Globals.FindCerts(),
	}
	if r.Method == "POST" && r.FormValue("_method") != "" {
		r.Method = r.FormValue("_method")
	}
	epname, ok := vars["name"]
	if !ok || epname == "" {
		logging.LogForRequest(logEP, r).Error("admin.endpointPageHandler missing name", "vars", vars)
		http.Error(w, "Missing name", http.StatusBadRequest)
		return
	}

	newEp := epname == "<new>"

	if !newEp {
		if ep := bctx.Globals.GetEndpoint(epname); ep != nil {
			ctx.Form.EndpointConf = ep.Clone()
		} else {
			logging.LogForRequest(logEP, r).Error("admin.endpointPageHandler ep not found", "endpoint", epname)
			http.Error(w, "Endpoint not found", http.StatusNotFound)
			return
		}
	} else {
		ctx.Form.EndpointConf = &config.EndpointConf{}
	}
	switch r.Method {
	case "POST":
		r.ParseForm()
		if err := decoder.Decode(&ctx.Form, r.Form); err != nil {
			logging.LogForRequest(logEP, r).Error("admin.endpointPageHandler decode form error", "err", err, "form", r.Form)
			break
		}
		if errors := ctx.Form.Validate(bctx.Globals, newEp); len(errors) > 0 {
			ctx.Form.Errors = errors
			break
		}
		bctx.Globals.SaveEndpoint(ctx.Form.EndpointConf)
		ctx.AddFlashMessage("Endpoint saved", "success")
		ctx.Save()
		http.Redirect(w, r, "/endpoints/", http.StatusFound)
		return
	}
	ctx.Save()
	RenderTemplateStd(w, ctx, "endpoints/endpoint.tmpl")

}
Exemple #26
0
func TestGetMatchingRoute_WithMethodOverrideParameter(t *testing.T) {

	var lastMethod string = ""

	DefaultRouteManager.ClearRoutes()

	MapFunc("/api", func(c *Context) {
		lastMethod = "GET"
	}, GetMethod)
	MapFunc("/api", func(c *Context) {
		lastMethod = "POST"
	}, PostMethod)
	MapFunc("/api", func(c *Context) {
		lastMethod = "PUT"
	}, PutMethod)
	MapFunc("/api", func(c *Context) {
		lastMethod = "DELETE"
	}, DeleteMethod)

	// make test objects
	var testResponse http.ResponseWriter = new(TestResponseWriter)
	var testRequest *http.Request = new(http.Request)
	var u *url.URL

	testRequest.Method = "GET"

	// handle the request
	u, _ = url.Parse(testDomain + "/api")
	testRequest, _ = http.NewRequest("GET", u.String(), nil)
	DefaultHttpHandler.ServeHTTP(testResponse, testRequest)
	if lastMethod != "GET" {
		t.Errorf("ServeHTTP with no method override parameter should the actual HTTP method.  GET expected but was '%s'", lastMethod)
	}

	u, _ = url.Parse(testDomain + "/api?" + REQUEST_METHOD_OVERRIDE_PARAMETER + "=post")
	testRequest, _ = http.NewRequest("GET", u.String(), nil)
	DefaultHttpHandler.ServeHTTP(testResponse, testRequest)
	if lastMethod != "POST" {
		t.Errorf("ServeHTTP with method override parameter should use that method instead.  POST expected but was '%s'", lastMethod)
	}

	u, _ = url.Parse(testDomain + "/api?" + REQUEST_METHOD_OVERRIDE_PARAMETER + "=Put")
	testRequest, _ = http.NewRequest("GET", u.String(), nil)
	DefaultHttpHandler.ServeHTTP(testResponse, testRequest)
	if lastMethod != "PUT" {
		t.Errorf("ServeHTTP with method override parameter should use that method instead.  PUT expected but was '%s'", lastMethod)
	}

	u, _ = url.Parse(testDomain + "/api?" + REQUEST_METHOD_OVERRIDE_PARAMETER + "=DELETE")
	testRequest, _ = http.NewRequest("GET", u.String(), nil)
	DefaultHttpHandler.ServeHTTP(testResponse, testRequest)
	if lastMethod != "DELETE" {
		t.Errorf("ServeHTTP with method override parameter should use that method instead.  DELETE expected but was '%s'", lastMethod)
	}

}
Exemple #27
0
func UnbindApp(w http.ResponseWriter, r *http.Request) error {
	r.Method = "POST"
	name := r.URL.Query().Get(":name")
	appHost := r.FormValue("app-host")
	err := unbind(name, appHost)
	if err == nil {
		w.WriteHeader(http.StatusOK)
	}
	return err
}
Exemple #28
0
// This method handles all requests.  It dispatches to handleInternal after
// handling / adapting websocket connections.
// To handle a Websocket connection:
// Add a route using the WS method.
// Add an action that accepts a *websocket.Conn parameter.
// For example, add this your routes file:
// 		WS /app/feed Application.Feed
// Then write an action like this:
//
// 		import "code.google.com/p/go.net/websocket"
// 		func (c Application) Feed(user string, ws *websocket.Conn) revel.Result {
// 			...
// 		}
func handle(w http.ResponseWriter, r *http.Request) {
	if r.Header.Get("Upgrade") == "websocket" {
		websocket.Handler(func(ws *websocket.Conn) {
			r.Method = "WS"
			handleInternal(w, r, ws)
		}).ServeHTTP(w, r)
	} else {
		handleInternal(w, r, nil)
	}
}
Exemple #29
0
func basicauthConnect(conn *streamConn) (*http.Response, error) {
	if conn.isStale() {
		return nil, errors.New("Stale connection")
	}

	conn.client = &http.Client{}
	if conn.insecure {
		conn.client.Transport = &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
	}

	var req http.Request
	req.URL = conn.url
	req.Method = "GET"
	req.Header = http.Header{}
	if conn.authData != "" {
		req.Header.Set("Authorization", conn.authData)
	}

	if conn.postData != "" {
		req.Method = "POST"
		req.Body = nopCloser{bytes.NewBufferString(conn.postData)}
		req.ContentLength = int64(len(conn.postData))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}
	Debug(req.Header)
	Debug(conn.postData)
	resp, err := conn.client.Do(&req)

	if err != nil {
		Log(ERROR, "Could not Connect to Stream: ", err)
		return nil, err
	} else {
		Debugf("connected to %s \n\thttp status = %v", conn.url, resp.Status)
		Debug(resp.Header)
		for n, v := range resp.Header {
			Debug(n, v[0])
		}
	}

	return resp, nil
}
Exemple #30
0
func reverseProxy(w http.ResponseWriter, req *http.Request) {
	logRequest(req)

	if rSensitivePath.MatchString(req.URL.Path) {
		w.WriteHeader(http.StatusForbidden)
		return
	}

	outReq := new(http.Request)
	outReq.Method = req.Method
	outReq.URL = &url.URL{
		Scheme:   "http",
		Host:     host,
		Path:     req.URL.Path,
		RawQuery: req.URL.RawQuery,
	}
	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1
	outReq.Header = make(http.Header)
	outReq.Body = req.Body
	outReq.ContentLength = req.ContentLength
	outReq.Host = host

	for _, h := range removeHeaders {
		req.Header.Del(h)
	}
	copyHeader(outReq.Header, req.Header)
	outReq.Header.Set("Host", host)
	outReq.Header.Set("Referer", baseURL)
	outReq.Header.Set("Origin", baseURL)

	resp, err := send(outReq)
	if err != nil {
		log.Printf("proxy error: %v", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()

	for _, h := range removeHeaders {
		resp.Header.Del(h)
	}
	if loc := resp.Header.Get("Location"); loc != "" {
		if u, err := url.Parse(loc); err == nil && u.Host == host {
			u.Scheme = "http"
			u.Host = req.Host
			resp.Header.Set("Location", u.String())
		}
	}
	copyHeader(w.Header(), resp.Header)
	w.WriteHeader(resp.StatusCode)

	io.Copy(w, resp.Body)
}