woodpecker/shared/httputil/httputil.go

69 lines
1.8 KiB
Go
Raw Permalink Normal View History

2018-02-19 22:24:10 +00:00
// Copyright 2018 Drone.IO Inc.
2018-03-21 13:02:17 +00:00
//
2018-02-19 22:24:10 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2018-03-21 13:02:17 +00:00
//
2018-02-19 22:24:10 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
2018-03-21 13:02:17 +00:00
//
2018-02-19 22:24:10 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2014-06-04 21:25:38 +00:00
package httputil
import (
2024-03-15 17:00:25 +00:00
"math"
2014-06-04 21:25:38 +00:00
"net/http"
"strings"
)
// IsHTTPS is a helper function that evaluates the http.Request
2014-06-04 21:25:38 +00:00
// and returns True if the Request uses HTTPS. It is able to detect,
// using the X-Forwarded-Proto, if the original request was HTTPS and
// routed through a reverse proxy with SSL termination.
func IsHTTPS(r *http.Request) bool {
2014-06-04 21:25:38 +00:00
switch {
case r.URL.Scheme == "https":
return true
2014-10-15 11:51:05 +00:00
case r.TLS != nil:
return true
2014-06-04 21:25:38 +00:00
case strings.HasPrefix(r.Proto, "HTTPS"):
return true
case r.Header.Get("X-Forwarded-Proto") == "https":
return true
default:
return false
}
}
// SetCookie writes the cookie value.
func SetCookie(w http.ResponseWriter, r *http.Request, name, value string) {
cookie := http.Cookie{
Name: name,
Value: value,
Path: "/",
Domain: r.URL.Host,
HttpOnly: true,
Secure: IsHTTPS(r),
2024-03-15 17:00:25 +00:00
MaxAge: math.MaxInt32, // the cookie value (token) is responsible for expiration
2014-06-04 21:25:38 +00:00
}
http.SetCookie(w, &cookie)
}
// DelCookie deletes a cookie.
func DelCookie(w http.ResponseWriter, r *http.Request, name string) {
cookie := http.Cookie{
Name: name,
Value: "deleted",
Path: "/",
Domain: r.URL.Host,
MaxAge: -1,
}
http.SetCookie(w, &cookie)
}