github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/html/cookie_del.go (about)

     1  package html
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/drivers"
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    10  )
    11  
    12  // COOKIE_DEL gets a cookie from a given page by name.
    13  // @param {HTMLPage} page - Target page.
    14  // @param {HTTPCookie, repeated | String, repeated} cookiesOrNames - Cookie or cookie name to delete.
    15  func CookieDel(ctx context.Context, args ...core.Value) (core.Value, error) {
    16  	err := core.ValidateArgs(args, 2, core.MaxArgs)
    17  
    18  	if err != nil {
    19  		return values.None, err
    20  	}
    21  
    22  	page, err := drivers.ToPage(args[0])
    23  
    24  	if err != nil {
    25  		return values.None, err
    26  	}
    27  
    28  	inputs := args[1:]
    29  	var currentCookies *drivers.HTTPCookies
    30  	cookies := drivers.NewHTTPCookies()
    31  
    32  	for _, c := range inputs {
    33  		switch cookie := c.(type) {
    34  		case values.String:
    35  			if currentCookies == nil {
    36  				current, err := page.GetCookies(ctx)
    37  
    38  				if err != nil {
    39  					return values.None, err
    40  				}
    41  
    42  				currentCookies = current
    43  			}
    44  
    45  			found, isFound := currentCookies.Get(cookie)
    46  
    47  			if isFound {
    48  				cookies.Set(found)
    49  			}
    50  
    51  		case drivers.HTTPCookie:
    52  			cookies.Set(cookie)
    53  		default:
    54  			return values.None, core.TypeError(c.Type(), types.String, drivers.HTTPCookieType)
    55  		}
    56  	}
    57  
    58  	return values.None, page.DeleteCookies(ctx, cookies)
    59  }