-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsunset.go
More file actions
61 lines (52 loc) · 1.53 KB
/
sunset.go
File metadata and controls
61 lines (52 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// SPDX-License-Identifier: EUPL-1.2
package api
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// ApiSunset returns middleware that marks a route or group as deprecated.
//
// The middleware appends standard deprecation headers to every response:
// Deprecation, optional Sunset, optional Link, and X-API-Warn. Existing header
// values are preserved so downstream middleware and handlers can keep their own
// link relations or warning metadata.
//
// Example:
//
// rg.Use(api.ApiSunset("2025-06-01", "/api/v2/users"))
func ApiSunset(sunsetDate, replacement string) gin.HandlerFunc {
sunsetDate = strings.TrimSpace(sunsetDate)
replacement = strings.TrimSpace(replacement)
formatted := formatSunsetDate(sunsetDate)
warning := "This endpoint is deprecated."
if sunsetDate != "" {
warning = "This endpoint is deprecated and will be removed on " + sunsetDate + "."
}
return func(c *gin.Context) {
c.Next()
c.Writer.Header().Add("Deprecation", "true")
if formatted != "" {
c.Writer.Header().Add("Sunset", formatted)
}
if replacement != "" {
c.Writer.Header().Add("Link", "<"+replacement+">; rel=\"successor-version\"")
}
c.Writer.Header().Add("X-API-Warn", warning)
}
}
func formatSunsetDate(sunsetDate string) string {
sunsetDate = strings.TrimSpace(sunsetDate)
if sunsetDate == "" {
return ""
}
if strings.Contains(sunsetDate, ",") {
return sunsetDate
}
parsed, err := time.Parse("2006-01-02", sunsetDate)
if err != nil {
return sunsetDate
}
return parsed.UTC().Format(http.TimeFormat)
}