Created
February 23, 2023 15:04
-
-
Save rueian/b25112d7ff4ed813f208d3e4797e96cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"net/http/httputil" | |
) | |
func main() { | |
// create a new proxy server | |
proxy := &httputil.ReverseProxy{ | |
Director: func(req *http.Request) { | |
// set the target host for the proxy server | |
req.URL.Scheme = "http" | |
req.URL.Host = "localhost:8080" | |
}, | |
} | |
// create a new http server to listen for incoming requests | |
server := &http.Server{ | |
Addr: ":8888", | |
Handler: proxy, | |
} | |
// add a log handler for incoming requests | |
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { | |
requestDump, err := httputil.DumpRequest(req, true) | |
if err != nil { | |
log.Printf("Error dumping request: %v", err) | |
} | |
log.Printf("Incoming request:\n%s", string(requestDump)) | |
proxy.ServeHTTP(w, req) | |
}) | |
// add a log handler for outgoing responses | |
proxy.ModifyResponse = func(resp *http.Response) error { | |
responseDump, err := httputil.DumpResponse(resp, true) | |
if err != nil { | |
log.Printf("Error dumping response: %v", err) | |
} | |
log.Printf("Outgoing response:\n%s", string(responseDump)) | |
return nil | |
} | |
// start the server | |
log.Println("Starting proxy server on :8888...") | |
err := server.ListenAndServe() | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
------------ | |
------------ | |
------------ | |
package main | |
import ( | |
"log" | |
"net/http" | |
"time" | |
"github.com/gin-gonic/gin" | |
"github.com/golang-jwt/jwt" | |
) | |
// Define a custom claims struct that will be encoded into a JWT. | |
type CustomClaims struct { | |
Username string `json:"username"` | |
jwt.StandardClaims | |
} | |
func main() { | |
// Create a new Gin router. | |
router := gin.Default() | |
// Define a middleware function that will check the JWT token. | |
authMiddleware := func() gin.HandlerFunc { | |
return func(c *gin.Context) { | |
// Get the Authorization header. | |
authHeader := c.GetHeader("Authorization") | |
// Check if the Authorization header is empty. | |
if authHeader == "" { | |
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"}) | |
return | |
} | |
// Parse the JWT token from the Authorization header. | |
token, err := jwt.ParseWithClaims(authHeader, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) { | |
// Make sure that the signing method is HMAC. | |
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { | |
return nil, jwt.ErrSignatureInvalid | |
} | |
// Return the secret key used to sign the JWT token. | |
return []byte("secret"), nil | |
}) | |
// Check if there was an error parsing the JWT token. | |
if err != nil { | |
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"}) | |
return | |
} | |
// Check if the token is valid. | |
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { | |
// Set the username from the JWT token in the context. | |
c.Set("username", claims.Username) | |
c.Next() | |
} else { | |
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"}) | |
} | |
} | |
}() | |
// Add a middleware to log incoming requests. | |
router.Use(func(c *gin.Context) { | |
// Log the request method and path. | |
log.Printf("Incoming request: %s %s", c.Request.Method, c.Request.URL.Path) | |
// Record the start time of the request. | |
start := time.Now() | |
// Process the request. | |
c.Next() | |
// Calculate the duration of the request. | |
duration := time.Since(start) | |
// Log the response status and duration. | |
log.Printf("Outgoing response: %d (%s)", c.Writer.Status(), duration) | |
}) | |
// Define a handler function that requires authentication. | |
router.GET("/api/hello", authMiddleware, func(c *gin.Context) { | |
// Get the username from the context. | |
username, exists := c.Get("username") | |
if !exists { | |
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Unable to retrieve username from context"}) | |
return | |
} | |
// Return a JSON response. | |
c.JSON(http.StatusOK, gin.H{"message": "Hello, " + username.(string) + "!"}) | |
}) | |
// Start the web server. | |
if err := router.Run(":8080"); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment